jQuery on()stopPropagation不工作?
我似乎无法让这个停止传播..
$(document).ready(function(){ $("body").on("click","img.theater",function(event){ event.stopPropagation(); $('.theater-wrapper').show(); }); // This shouldn't fire if I click inside of the div that's inside of the // `.theater-wrapper`, which is called `.theater-container`, anything else it should. $(".theater-wrapper").click(function(event){ $('.theater-wrapper').hide(); }); });
请参考这个jsfiddle
因为你正在使用body
元素而不是直接在img.theater
上img.theater
所以事件将会冒泡到body
元素,这就是它的工作原理。
在事件冒泡过程中, .theater-wrapper
元素将触发click
事件,以便您可以看到它。
如果您没有创建任何动态元素,则直接在img.theater
元素上附加click事件处理程序。
$("img.theater").click(function(event){ event.stopPropagation(); $('.theater-wrapper').show(); });
或者,你可以检查里面的click
事件的目标.theater-wrapper
elements click
handler并且什么都不做。
$(".theater-wrapper").click(function(event){ if ($(event.target).is('img.theater')){ event.stopPropagation(); return; } $('.theater-wrapper').hide(); });
最好的方法是:
$(".theater-wrapper").click(function(event){ if (!$(event.target).is('img.theater')){ $('.theater-wrapper').hide(); } });
这对我来说是手风琴和复选框
响应你的jsfiddle @Dylan
这里:当你点击白点时它不应该关闭。 jsfiddle.net/Cs8Kq – 迪伦
更改
if ($(event.target).is('img.theater')){
至
if ($(event.target).is('.theater-container')){
它会起作用。
我通过在事件处理程序中使用console.log(event.target)解决了这个问题,并且只使用了当我点击你所说的白色区域时已经注销的选择器。
我会反过来评论,但我没有足够的SO stardust和硬币。
编辑:像这样jsfiddle.net/heNP4/