繁体   English   中英

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

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

您好我已经看过类似的帖子,但没有人回答我想要完成的事情我在这里做了一个示例http://jsfiddle.net/edgardo400/R6rVJ/

我基本上想要的是当父母点击发生你得到孩子的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

如果您只希望使代码正常工作并在控制台上显示框名称,则应该设置

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

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

     /* rest of your code */
});

您可能想要做一些更容易的事情

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

   jQuery(this).delegate... 

});

虽然我不确定你为什么要这样做......

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

在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