开发者

Get id of children

I have made a dynamic system so you can append divs in divs in divs etc. Now I want to know the id of the div when I click on it. I have made a script like this: HTML:

<div id="div1" class="mod">   
  <di开发者_运维问答v id="div4" class="mod">
     <div id="div5" class="mod"></div>
  </div>
</div>
<div id="div2" class="mod">
   <div id="div6" class="mod">
     <div id="div7" class="mod"></div>
   </div>
</div>

Jquery:

$('.mod').click(function(){
  var id = $(this).attr('id');
  alert(id);
 });

If you click for example on div4 it will return div_4 and div_1 but I only want div_4 as return. Can someone help me? I read something about parents and children but I can't figure it out. Regards Frank


You can stop the bubbling of the event with:

$('.mod').click(function(event){
  var id = $(this).attr('id');
  alert(id);
  event.stopPropagation();
});

The click-event then should only reach the highest layer/div.


Don't add click events to every element. Add one click event to the container of all of the divs, and then use the jquery event object to get the target element that was clicked.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜