Select only parent, exclude everything else while click()

久未见 提交于 2020-01-03 19:03:46

问题


I have a #container and buttons which are children to this container. When I click the container itself (the white space around the buttons), I want it to change its background color but I want nothing to happen when I click the buttons.

Selecting the #container in jquery, though, makes clicking the buttons change the bg as well...

<div id="container">
   <div class="button>
      <span class="text">Button 1</span>
   </div>
   <div class="button>
      <span class="text">Button 2</span>
   </div>
</div>

$("#container").click(function() {
   $('#container').css({background: 'blue'});
});

I've tried many things, nothing seems to be working.


回答1:


Examine the original target of the event:

$("#container").click(function(event) {
   if(event.target === this) {
       $('#container').css({background: 'blue'});
   }
});

Reference: event.target




回答2:


There is a simpler another solution:

$('#container button').click(function(event) {
    event.stopPropagation();
});



回答3:


Check the id when clicking, so you don't pick up the buttons.

$("#container").click(function(event) {
   if(event.target.id === "container") {
       $('#container').css({background: 'blue'});
   }
});


来源:https://stackoverflow.com/questions/7299897/select-only-parent-exclude-everything-else-while-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!