![](/img/trans.png)
[英]JavaScript: Event listener for multiple buttons with same class name
[英]Event Listener for click event on multiple buttons of same name but different value
修改后的工作方式:jQuery和Bootstrap不允許使用相同的ID-請參見以下新的UI和Jquery代碼:
以前嘗試按照最新安全性實踐的建議將onclick事件與UI完全分開。 即使在使用“ this”的情況下,在Jquery和Javascript中使用重復ID也會對onclick事件造成不良影響,而是在Twitter引導類后面使用鏈接類(空類),並將onclick綁定到新的自定義類。 這消除了在線單擊事件。
更新的UI代碼:
//Grid Row 1 with record info preceeding
<td>
<button type='button' class='btn btn-default btn-xs cust_delete' id='btn_delete_record_1' name='btn_delete_record_1' value="X38-721" data-toggle='modal' data-target='#DeleteRecordModal'>
<span class='glyphicon glyphicon-trash'></span>
</button>
</td>
//Grid Row 2 with record info preceeding
<td>
<button type='button' class='btn btn-default btn-xs cust_delete' id='btn_delete_record_2' name='btn_delete_record_2' value="X34-7245" data-toggle='modal' data-target='#DeleteRecordModal'>
<span class='glyphicon glyphicon-trash'></span>
</button>
</td>
JQUERY-
$( document ).ready(function() {
$('.cust_view').click(function() {
var myRecord = $(this).attr('value');
$("#view_record_id").val(myRecord);
$('form#frm_view_record').submit();
});
$('.cust_delete').click(function() {
var myRecord = $(this).attr('value');
$('#delete_record_id').val(myRecord);
});
});
使用document.querySelectorAll()
循環遍歷按鈕名稱為“ button”的所有事件,並向其添加addEventListener()
。 這些按鈕可以具有不同的值,但是它僅檢查名稱:
var linkListener = document.querySelectorAll("button[name='button']"); for (i=0;i<linkListener.length;i++){ linkListener[i].addEventListener("click", linkFunction); } function linkFunction(){ alert("You clicked a button with a \\"name\\" of \\"button\\"."); }
<button name="button">A button</button><button name="button">A button</button><button name="button">A button</button><button name="button">A button</button><button name="button">A button</button><button name="button">A button</button><button name="button">A button</button><br/><br/> <button name="button1">A button</button><button name="button2">A button</button><button name="button3">A button</button><button name="button4">A button</button><button name="button5">A button</button><button name="button6">A button</button><button name="button7">A button</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.