简体   繁体   中英

JS (Coffee-Script) is not working in rails app

I am writing a simple code like:

ready = ->
  $('div').click ->
  $(this).append "<span style='color:#f00;'>olol</span>"
$(document).ready(ready)
$(document).on('page:load', ready)

However nothing happens, when I click on div elements on my web-page. When I put it into the HTML file between tags everything works!!! Please, help, it seems, that I've tried everything!

You're not properly indenting the body of the click handler. This part:

$('div').click ->
$(this).append "<span style='color:#f00;'>olol</span>"

Will compile to:

$('div').click(function() {});

$(this).append("<span style='color:#f00;'>olol</span>");

As you can see the function in your click handler is empty. Fix it by indenting that second line:

$('div').click ->
  $(this).append "<span style='color:#f00;'>olol</span>"

Now that compiles as expected:

$('div').click(function() {
  return $(this).append("<span style='color:#f00;'>olol</span>");
});

Be mindful of whitespace when writing Coffeescript.

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