[英]JS script works only when embedded in scala/html code
I've a div like this in a scala.html file of my template (I'm using PlayFramework): 我在我的模板的scala.html文件中有这样的div(我正在使用PlayFramework):
<div id="box">Text in the box</div>
and this Coffee script: 和这个咖啡脚本:
$("#box").on "click", ->
$("#box").fadeOut()
It doesn't work: if I click the div #box nothing happens. 它不起作用:如果我点击div #box没有任何反应。 I'm trying to use plain jquery to understand if it's a Coffee issue or not. 我正在尝试使用普通的jquery来理解它是否是咖啡问题。 Then I put the same jQuery script in <head>
: 然后我在<head>
放入相同的jQuery脚本:
<script>
$("#box").on("click", function() {
return $("#box").fadeOut();
});
</script>
and doesn't work again but if I put it in the scala.html file (that contains the div #box) it works! 并且不再工作,但如果我把它放在scala.html文件(包含div #box)中它可以工作! Where is the error? 错误在哪里?
the div#box is loaded with an Ajax call by clicking a button, then before loading it doesn't exist. div#框通过单击按钮加载Ajax调用,然后在加载之前它不存在。 Is it the problem? 这是问题吗?
Yeah, that would cause it. 是的,这会导致它。 And, delegated binding is generally the solution. 并且, 委托绑定通常是解决方案。
The reason for it is because jQuery can only bind events to elements that exist at that moment. 之所以这样,是因为jQuery只能将事件绑定到当时存在的元素。 But, since nearly all events bubble/propagate through the target
's .parents()
, an existing parent can be used to represent the intended descendant. 但是,由于几乎所有事件都通过target
的.parents()
传播/传播,因此现有父级可用于表示预期的后代。
$(document).on 'click', '#box', ->
# ...
In this case, document
is the existing parent, allowing #box
to have a click
binding created for it before it exists in the DOM. 在这种情况下, document
是现有父级,允许#box
在DOM存在之前为其创建一个click
绑定。
Otherwise, the binding of the event can be delayed until the element exists. 否则,可以延迟事件的绑定,直到元素存在。 This is what happens for the last part of your question, as the <script>
is inserted into the DOM along with the <div>
. 这就是问题的最后部分所发生的情况,因为<script>
与<div>
一起插入到DOM中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.