2016-03-07 69 views
1

问题:我绑定一个单击事件的函数在绑定上触发。函数在绑定上执行而不是点击

我发现其他人有这个相同的问题,并找到了一些答案。但是,在实施这些解决方案时,我仍然看到同样的问题。我一定在做错事,但我似乎无法弄清楚。

演示问题: https://jsfiddle.net/b35krwfh/16/

代码(CoffeeScript中)的原始片段,被调用的绑定功能:

$("body").bind "click", deviceCloseView 

一些在线研究之后,我发现了以下的建议修复,但我仍然遇到同样的问题:

$("body").bind "click", -> 
    deviceCloseView() 

更新:有人建议我删除括号,但是似乎并没有解决这个问题,因为它没有执行在所有的时候我这样做:

jQuery function called in a .bind click handler is running on document ready

$("body").bind "click", -> 
    deviceCloseView 

https://jsfiddle.net/b35krwfh/15/

我曾经试图解决这一问题的一些参考

Why does click event handler fire immediately upon page load?

+1

似乎无法重现此。 '$(“body”).bind“click”,deviceCloseView'按预期工作,因为它在“click”上调用函数。 –

+0

你确定吗?我已经做了一个jsfiddle演示它,而deviceOpenView执行。 deviceCloseView不。 https://jsfiddle.net/b35krwfh/12/ – Nil

+0

在寻求帮助之前,您可能需要进行一些调试,只需要一些'console.log'调用(https://jsfiddle.net/ck51y35b /)会显示你的代码没有达到你期望的效果。点击图像打开它,然后立即关闭它。 –

回答

1

deviceOpenView在您的jsfiddle不停止传播o f点击事件。当您将deviceCloseView绑定到body时,它也会通过同样的点击触发。

您需要更改deviceOpenView才能停止click事件的传播以防止发生此情况。

deviceOpenView = (event) -> 
    event.stopPropagation(); 
    // ... your other code 
+0

啊,我明白了,非常感谢。现在阅读更多关于传播的知识,但这很有意义。赞赏。 – Nil

1

您的活动正在冒泡。这里有一个固定的小提琴: https://jsfiddle.net/6nk3asfw/

调用了preventDefault,stopPropagation,返回false,我只是做了所有的人:)

一些代码:

deviceOpenView = (e) -> 
    console.log("open"); 
    console.dir(e); 
    e.preventDefault(); 
    e.stopPropagation(); 
+0

就是这样,谢谢。我需要做更多关于传播的阅读。 – Nil

相关问题