简体   繁体   中英

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):

<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. I'm trying to use plain jquery to understand if it's a Coffee issue or not. Then I put the same jQuery script in <head> :

<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! Where is the error?

the div#box is loaded with an Ajax call by clicking a button, then before loading it doesn't exist. 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. But, since nearly all events bubble/propagate through the target 's .parents() , an existing parent can be used to represent the intended descendant.

$(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.

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM