开发者

Rails 3.1 loads scripts before the page is loaded. How to bind functions to page elements?

Putting this code in

$('#hello').click ->
  alert 'hello'

in posts.js.coffee in vanilla Rails 3.1 app does not work. The javascript is compiled and loaded before the page so the fun开发者_如何学Pythonction isn't bound to its element. There are easy solutions, like manually loading the js on the page rather than using the asset pipeline, or using JQuery .live functions, but it seems like this code should work out of the box. Am I missing something??


I might be pointing out the obvious here, but have you (in jQuery) tried this:

$(function(){    
    //your code
    $('#hello').click(function(){
    alert("hello");
    });
});

or

$(document).ready(function(){ [...] });

These (atleast under normal circumstances) should prevent any javascript inside from doing anything until the DOM has been loaded.

Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜