2013-11-27 58 views
5

我有一個使用coffeescript的rails應用程序。當我刷新頁面或直接使用URL轉到頁面時,以下代碼可以工作。當我點擊一個鏈接到這個頁面並試用它時,它根本不起作用。爲什麼會這樣?Coffeescript JQuery on click only working when page is refreshd

jQuery -> 
    console.log "Ready." 
    $('form').on 'click', '.add_fields', (event) -> 
    console.log "Click." 
    time = new Date().getTime() 
    regexp = new RegExp($(this).data('id'), 'g') 
    $(this).before($(this).data('fields').replace(regexp, time)) 
    event.preventDefault() 

重新加載後,我得到就緒並單擊適當時,它的工作原理。在從另一個頁面點擊後,我什麼也沒得到。我也得到鉻這個折舊警告,這我不知道如何解決,因爲它是從內JQuery的本身來:

event.returnValue is deprecated. Please use the standard event.preventDefault() instead. 
jquery.js?body=1:5375 

錯誤只會顯示在上面的代碼無法正常工作。鉻是否阻擋它?我正在使用jquery-rails (3.0.4)

+1

是否使用Turbolinks?如果是這樣,當DOM被刷新時,表單上的處理程序就會被吹走。您需要將其包裝在頁面中:恢復頁面:加載類型處理程序。 – davidfurber

+0

是的,我。我一開始並沒有意識到我的身份。感謝那!! – mscriven

回答

6

所以事實證明,這是造成問題的turbolinks。謝謝davidburber指出這一點。下面是我做修復(從Rails 4: how to use $(document).ready() with turbo-links

ready = -> 
    $('form').on 'click', '.remove_fields', (event) -> 
    $(this).prev('input[type=hidden]').val('1') 
    $(this).closest('fieldset').hide() 
    event.preventDefault() 


$(document).ready(ready) 
$(document).on('page:load', ready) 
+1

也必須添加 $(document).on('turbolinks:load',ready); 得到這個工作 – user1130176

4

還有一個更簡單的這裏解決方案。

當您使用turbolinks,這是默認的,因爲軌道4,還包括[jquery.turbolinks寶石] [1]

的說明是很容易的。

  1. 在你的Gemfile添加:寶石 'jQuery的turbolinks'
  2. 在JavaScript清單(默認:應用程序/資產/ Java腳本/ application.js.coffee):
    要求jquery.turbolinks jquery後立即
    需要渦輪鏈接後你的腳本

例子:

#= require jquery 
#= require jquery.turbolinks 
#= require jquery_ujs 

# ... your other scripts here ... 

#= require turbolinks 


通過以上你既不需要在你的代碼也不行任何變化:

$(document).ready(ready) 
$(document).on('page:load', ready) 
+0

這對我的每一個問題除外.on'click'事件... –

相關問題