我的模板的 scala.html 文件中有一个像这样的 div(我正在使用 PlayFramework):
<div id="box">Text in the box</div>
还有这个 CoffeeScript :
$("#box").on "click", ->
$("#box").fadeOut()
它不起作用:如果我单击 div #box,则什么也不会发生。
我正在尝试使用普通的 jquery 来了解这是否是咖啡问题。然后我将相同的 jQuery 脚本放入 <head>
:
<script>
$("#box").on("click", function() {
return $("#box").fadeOut();
});
</script>
并且不再工作,但如果我将它放入 scala.html 文件(包含 div #box)中,它就可以工作! 错误在哪里?
最佳答案
the div#box is loaded with an Ajax call by clicking a button, then before loading it doesn't exist. Is it the problem?
是的,这会导致它。并且,delegated binding通常是解决方案。
这是因为 jQuery 只能将事件绑定(bind)到当时存在的元素。但是,由于几乎所有事件都通过 target
冒泡/传播。的 .parents()
,现有的父代可以用来代表预期的后代。
$(document).on 'click', '#box', ->
# ...
在本例中,document
是现有的父级,允许 #box
有一个click
在它存在于 DOM 中之前为其创建绑定(bind)。
否则,事件的绑定(bind)可以延迟到元素存在为止。这就是您问题的最后部分所发生的情况,如 <script>
与 <div>
一起插入到 DOM 中.
关于javascript - JS 脚本仅在嵌入 scala/html 代码中时才有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19446171/