2014-09-22 53 views
0

我有一个小jQuery的摘录这是工作,而wierdly只运行一次......如何使jQuery的嵌套标签

这里是jQuery的

$(document).ready(function() { 
 
    $("div").click(function (event) { 
 
     alert(event.target.id); 
 

 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="div1">div1 
 
    <div id="div2">div2 
 
     <div id="div3">div3 
 
      <div id="div4">div4</div> 
 
     </div> 
 
    </div> 
 
</div>

的问题是警报作品多次嵌套的div。为什么这样?

+1

因为click事件 “泡” 到最顶端的元素。 – Justinas 2014-09-22 07:23:30

回答

2

使用​​:停止泡沫

$("div").click(function (event) { 
     event.stopPropagation(); 
     alert(event.target.id); 

    }); 
1

这是因为冒泡和捕捉使用stopPropagation()方法

http://javascript.info/tutorial/bubbling-and-capturing

希望它可以帮助你

element.onclick = function(event) { 
    event = event || window.event // cross-browser event 

    if (event.stopPropagation) { 
     // W3C standard variant 
     event.stopPropagation() 
    } else { 
     // IE variant 
     event.cancelBubble = true 
    } 
} 
0

使用class在这方面

<div id="div1" class='myDiv'>div1 
    <div id="div2" class='myDiv'>div2 
     <div id="div3" class='myDiv'>div3 
      <div id="div4" class='myDiv'>div4</div> 
     </div> 
    </div> 
</div> 

jQuery的是

$(".myDiv").click(function (event) { 

     event.stopPropagation(); 
     $(this).attr('id'); 

});