Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 仅选择父项,在单击()时排除所有其他内容_Jquery_Jquery Selectors - Fatal编程技术网

Jquery 仅选择父项,在单击()时排除所有其他内容

Jquery 仅选择父项,在单击()时排除所有其他内容,jquery,jquery-selectors,Jquery,Jquery Selectors,我有一个容器和按钮,它们是这个容器的子对象。当我单击容器本身(按钮周围的空白处)时,我希望它更改其背景色,但我不希望在单击按钮时发生任何事情 $("#container").click(function(event) { if(event.target.id === "container") { $('#container').css({background: 'blue'}); } }); 不过,在jquery中选择#容器也会使单击按钮更改bg <div id

我有一个容器和按钮,它们是这个容器的子对象。当我单击容器本身(按钮周围的空白处)时,我希望它更改其背景色,但我不希望在单击按钮时发生任何事情

$("#container").click(function(event) {
   if(event.target.id === "container") {
       $('#container').css({background: 'blue'});
   }
});
不过,在jquery中选择#容器也会使单击按钮更改bg

<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'});
});

按钮2
$(“#容器”)。单击(函数(){
$('#container').css({background:'blue'});
});

我尝试了很多事情,但似乎没有任何效果。

检查活动的原始目标:

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

参考

单击时检查id,这样就不会选择按钮

$("#container").click(function(event) {
   if(event.target.id === "container") {
       $('#container').css({background: 'blue'});
   }
});
还有一个更简单的解决方案:

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

这似乎不起作用,不知道我是否做错了。