简体   繁体   English

单击父级时获取子元素的id

[英]get id of child element when parent is clicked

Hello I have seen similar posts but none answer what I want to accomplish I made a sample here http://jsfiddle.net/edgardo400/R6rVJ/ 您好我已经看过类似的帖子,但没有人回答我想要完成的事情我在这里做了一个示例http://jsfiddle.net/edgardo400/R6rVJ/

What i basically want is when a click happens in the parent you get the id of the child and store it in a variable so i can pass the variable currentID to the code below otherwise I will have to replicate this code 9 times for each id from box1 to box9 我基本上想要的是当父母点击发生你得到孩子的id并将其存储在一个变量中,所以我可以将变量currentID传递给下面的代码,否则我将不得不为每个id复制这个代码9次box1到box9

 jQuery(currentID).delegate("a", "hover", function(event){

        var $img = jQuery(this).parent("li").find('img');
        var image = jQuery(this).attr('data-img');
         jQuery('.defaultimg').stop(true, true).fadeOut();
        if( event.type === 'mouseenter' ) {

            if($img.length){
                $img.show();

            }else{
                jQuery(this).parent("li").append('<img id="theImg" src="' + image + '" />');
            }

        }else{
            if($img){
              $img.hide();  
            }
             jQuery('.defaultimg').stop(true, true).fadeIn();
        }
    });
});
$('#boxes').on('click', function(e) {
    var currentID = e.target.id;
    console.log(currentID);

......rest of code

If you only wish to make your code working and displaying on your console the box name, you should probably set 如果您只希望使代码正常工作并在控制台上显示框名称,则应该设置

jQuery('#boxes').bind('click', function(event) {

     var currentID = jQuery(event.srcElement).attr('id');

     /* rest of your code */
});

You might want to do something easier 您可能想要做一些更容易的事情

jQuery('#boxes').children().bind('click', function() {

   jQuery(this).delegate... 

});

Although I'm not sure why you are doing this ... 虽然我不确定你为什么要这样做......

fixed http://jsfiddle.net/nxTDA/ 固定http://jsfiddle.net/nxTDA/

In javascript it would be: 在javascript中它将是:

var a = document.getElementById('#boxes');
a.onclick = function(e){
    console.log(e.target.id);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM