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 捕获div中任何元素上的单击事件_Jquery_Onclick - Fatal编程技术网

Jquery 捕获div中任何元素上的单击事件

Jquery 捕获div中任何元素上的单击事件,jquery,onclick,Jquery,Onclick,我有一个div,它包含一组元素。如果屏幕大小小于767px,此div将被隐藏(动画fadeOut())。但是,如果用户单击此div中的任何元素,我想停止fadeOut() 但正如我现在所看到的,我必须为这个div中的每个元素添加一个click事件。有没有一种更优雅的方法来捕获div中的所有单击事件?您可以这样做: $('#container').on('click', function (event) { if (event.target != this) { alert('You

我有一个
div
,它包含一组元素。如果屏幕大小小于767px,此
div
将被隐藏(动画
fadeOut()
)。但是,如果用户单击此
div
中的任何元素,我想停止
fadeOut()


但正如我现在所看到的,我必须为这个
div
中的每个元素添加一个click事件。有没有一种更优雅的方法来捕获
div中的所有单击事件?

您可以这样做:

$('#container').on('click', function (event) {
  if (event.target != this) {
    alert('You clicked a descendent of #container.');
  } else {
    alert('You actually clicked #container itself.');
  }
});

这将检查发起单击事件的元素是否与它所连接的元素完全相同。

这只是Bill Chriswell答案的扩展,在该答案中,容器的子元素将侦听单击事件。要停止动画,可能需要使用方法

$(“#容器”).children().on('click',函数(e){
//在此处应用jQuery的stop()方法
警报(“子项”);
});

容器
跨度1跨度2

可能添加e.stopPropagation()