2016-03-02 58 views
1

我有一個動態創建的表格,它具有與之關聯的按鈕。我想要一個適用於每個按鈕的簡單JavaScript方法。現在,它僅引用創建的第一個按鈕。將javascript應用於所有按鈕

<table> 
<tbody> 
<% @task.subtasks.each do |subtask| %> 
    <tr> 
    <td> 
     <button class="btn btn-default" id="collapseBtn"><span class="glyphicon glyphicon-plus" id="collapseSpan"></button> 
    </td> 
    <td> <%= subtask.name %></td> 
    </tr> 
<%end%> 
</tbody> 
</table> 

<script> 
    $("#collapseBtn").click(function(){ 
     $("#collapseSpan).toggleClass("glyphicon-plus glyphicon-minus"); 
    }); 
</script> 
+0

如果添加類似'collapse-btn'並嘗試選擇類而不是id? – lintmouse

+0

[動態創建的元素上的事件綁定?]可能的重複?(http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) –

回答

2

id屬性必須是html頁面上的任何元素唯一的,所以你需要添加一些類來檢測你的按鈕時,其中的很多。然後處理該類別的按鈕

$(".buttonClass").on('click', function(e){ 
    $(this).find('span').toggleClass("glyphicon-plus glyphicon-minus"); 
}); 
+0

這很好。添加了一個if語句,一切都很好。謝謝! –

1

我看到你正在使用jQuery。
您可以選擇在jQuery的所有按鈕與

$(":button") 

而不是使用一個ID $("#collapseBtn")

然後使用$(this)函數來引用它。

來源:http://api.jquery.com/button-selector/