2016-10-13 25 views
0

如標題所示,單擊selection-table中的任何表格行都不會執行任何操作。第一個警報 - alert("It works on each visit!"); - 在每個頁面加載時運行。我試過.clickon('click',function)無濟於事。我想不出爲什麼這種方式不行,除了我在遍歷表格行時犯了一個愚蠢的/簡單的錯誤,我看不到。無法點擊Rails生成的表格行

$(document).on('turbolinks:load', function() { 
 
    alert("It works on each visit!"); 
 
    $('#selection-table tbody tr:not(:first-child)').each(function() { 
 
     $(this).click(function() { 
 
      alert("row clicked"); 
 
      var ID = $(this).first().html(); 
 
      $('#tokemon_trainer_id').val(ID); 
 
     }); 
 
    }); 
 
});
<table id="selection-table" class="w3-table w3-striped w3-bordered w3-border w3-hoverable" > 
 
     <tr> 
 
     <th>ID</th> 
 
     <th>Name</th> 
 
     </tr> 
 
     <% @list_of_trainers.each do |trainer| %> 
 
     <tr class="selection-row"> 
 
     <td><%= trainer.id %></td> 
 
     <td><%= trainer.name %></td> 
 
     </tr> 
 
     <% end %> 
 
    </table>

回答

0

從turbolinks文檔:

如果可能,應避免使用turbolinks:負載事件 偵聽器添加事件直接對頁面體元件。相反,請考慮 使用事件委託在文檔或 窗口上註冊一次事件偵聽器。

他們使這個建議,因爲他們不能保證turbolinks:load文檔完成加載之前不會發生(即你的行可能實際上並不存在 - 所以沒有什麼會得到附後)。下面的代碼使用事件委託。

$(document).on('click', '#selection-table tbody tr:not(:first-child)', function() { 
    alert("row clicked"); 
    var ID = $(this).first().html(); 
    $('#tokemon_trainer_id').val(ID); 
}); 

$(document).on('click', '#selection-table tbody tr:not(:first-child)', function() { 
 
    console.log("row clicked"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 
\t <div id='result'></div> 
 
<table id="selection-table"> 
 
    <tr> 
 
    <th>ID</th> 
 
    <th>Name</th> 
 
    </tr> 
 
    <tr class="selection-row"> 
 
    <td><%= trainer.id %></td> 
 
    <td><%= trainer.name %></td> 
 
    </tr> 
 
</table> 
 
</body>

+0

感謝您的建議,但它仍然無法正常工作。我看了一下事件代表團,你的代碼確實有道理。也許我正確使用rails資產管道?我有'assets/javascripts'文件夾中的JS文件,我認爲它是清單文件中的正確內容。我已經安裝了'gem jquery-rails',並且在application.html.erb中有'<%= javascript_include_tag'應用程序','data-turbolinks-track':'reload'%>'。不知道現在該做什麼。 – Extreme112

+0

從來沒有使用turborails對不起,不能幫助它的那部分。可能是一個想法,把它放在一個jsfiddle。我驗證了上面的代碼是正確的(請參閱代碼段)。可能是一個'id'問題或表結構問題 – Tibrogargan

+0

@ Extreme112這可能是一個想法,看看呈現的表的來源。可能會提供更多的線索。或者將點擊選擇器改爲「'.selection-row'」而不是'#selection-table tbody tr:not(:first-child)'' – Tibrogargan