簡體   English   中英

我如何為 forwach 循環中的按鈕創建事件偵聽器

[英]how do i make a event listener for a button that is in a forwach loop

我有一個for 每個循環,它循環遍歷一個表,並且該表有一個id字段,該字段被分配給按鈕的id 我需要查看點擊了哪個按鈕(我需要獲取id的值)。 表的id不是1,2,3,4,5它是帶有數字的QA 例如,一個按鈕的id可能是: Q21

這可能會讓你開始:

 $('table tr td button').click(function(){ let tbl = $(this).closest('table').attr('id'); let row = $(this).closest('tr')[0].rowIndex; console.log(tbl+row); });
 .h2{font-size:1.5rem;} .h3{font-style:italic;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <div class="h2">Table rowIndex is zero-based</div> <div class="h3">(First row number is zero)</div> <table id="Q"> <tr><td>Row 1</td><td><button>Row 1</button></td></tr> <tr><td>Row 2</td><td><button>Row 2</button></td></tr> <tr><td>Row 3</td><td><button>Row 3</button></td></tr> </table>

在看到您的最新評論回復之前,我寫了較早的答案。 這個新答案可能更接近您的需要。 我將留下第一個答案,以便您以后可以參考。

 $('table tr td button').click(function(){ let buttId = this.id; console.log('You clicked: ' + buttId); });
 .h2{font-size:1.5rem;} .h3{font-style:italic;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <div class="h2">This might be closer to your needs</div> <table id="Q"> <tr><td>Row 1</td><td><button id="Q1">Row 1</button></td></tr> <tr><td>Row 2</td><td><button id="Q2">Row 2</button></td></tr> <tr><td>Row 3</td><td><button id="Q3">Row 3</button></td></tr> </table>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM