简体   繁体   中英

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

I have a for each loop where it loops through a table and the table has an id field which gets assigned to the button's id . I need to see which button gets clicked (I need to get the value of the id ). the id of the table is not 1,2,3,4,5 it is either a Q or A with a number; eg one button's id might be: Q21 .

This might get you started:

 $('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>

I wrote the earlier answer before I saw your latest comment reply. This new answer might be closer to what you need. I will leave the first answer so you can refer to it later if you wish.

 $('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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM