开发者

Combined div elements combined with jQuery

开发者 https://www.devze.com 2023-03-11 01:12 出处:网络
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 seco

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

精彩评论

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

关注公众号