开发者

Combined div elements combined with jQuery

I got an html page like this:

<div id="foo">
  first
  <div>
    second
  </div>
</div>

Now, I want to use the jQuery click method but should only work when clicking first, not second. But if doing something like

$("#foo").click(function() { do things });

If I click inside the second, its like clicking also on the first and the above function will run. Can I avoid this? So, clicking in second, wo开发者_开发知识库n't run the above function of the first?


Yes you can!

$("#foo div.second").click(function(event) {
    event.stopPropagation();
});

That will stop propagation to elements "above" in the tree.


$('#foo').click(function(e) {
    // Do your snazzy stuff.
});

$('#foo div').click(function(e) {
    e.stopPropagation();
});

= OR =

$('#foo').children().click(function(e) {
   e.stopPropagation();
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜