2013-03-22 25 views
0

我想在Rails網站的頁面中隱藏一個元素,但我還不熟悉Jquery或Coffeescript。如何在Rails中使用jQuery和Coffeescript來隱藏元素?

此代碼在控制檯:

$('#TheButton').click(function(){$('#TheText').toggle()}); 

然後我converted它Coffescript:

$("#TheButton").click -> 
    $("#TheText").toggle() 

但它不我的Rails頁面上工作。我如何解決它?下面是生成的JavaScript文件:

(function() { 
jQuery(function() { 
# stuff... 
    }); 

    $('form').on('click', '.add_fields', function(event) { 
    # stuff... 
    }); 

    $("#TheButton").click(function() { 
    return $("#TheText").toggle(); 
    }); 

}).call(this); 

回答

2

如果你的JS文件嵌入在佈局的頂部,每個文件你必須包裹在jQuery的通話

+0

好的,謝謝,我不得不在'$(「#TheButton」)代碼之前添加'jquery - >'。 – 2013-03-22 22:36:02

0

jQuery的選擇並不直到工作後,該頁面已加載。你需要確保你的代碼運行後的文件已準備就緒:

$(document).ready -> 

    $("#TheButton").click -> 
    $("#TheText").toggle() 

    # other stuff you want to happen after document load 
0

添加

$ -> 

代碼之前,以確保它在加載DOM後運行。