Task setting . The table must be equipped with the ability to delete certain lines from it. Click on the word delete in the line -> a modal menu opens, where the user is asked again what exactly to delete or to cancel. Clicking on the button of the modal window "Delete" from the table should disappear the corresponding row.
Markup
There is a markup c table. Two columns, the first with an identifier, and the second with some text. The first line is the header, and the left ones are normal lines:
<table id="table_main"> <tr> <th>id</th> <th>Π’Π΅ΠΊΡΡ Π·Π°Π΄Π°ΡΠΈ</th> <th>ΠΠ΅ΠΉΡΡΠ²ΠΈΡ</th> </tr> <tr> <td>1</td> <td>Π’Π΅ΠΊΡΡ 1</td> <td><p class="delete">Π£Π΄Π°Π»ΠΈΡΡ</p></td> </tr> <tr> <td>2</td> <td>Π’Π΅ΠΊΡΡ 2</td> <td><p class="delete">Π£Π΄Π°Π»ΠΈΡΡ</p></td> </tr> <tr> <td>3</td> <td>Π’Π΅ΠΊΡΡ 3</td> <td><p class="delete">Π£Π΄Π°Π»ΠΈΡΡ</p></td> </tr> <tr> <td>4</td> <td>Π’Π΅ΠΊΡΡ 4</td> <td><p class="delete">Π£Π΄Π°Π»ΠΈΡΡ</p></td> </tr> <tr> <td>5</td> <td>Π’Π΅ΠΊΡΡ 5</td> <td><p class="delete">Π£Π΄Π°Π»ΠΈΡΡ</p></td> </tr> <tr> <td>6</td> <td>Π’Π΅ΠΊΡΡ 6</td> <td><p class="delete">Π£Π΄Π°Π»ΠΈΡΡ</p></td> </tr> </table> And the modal window:
<div class="modal_delete"> <div id="modal_button_container"> <button id="button_delete">Π£Π΄Π°Π»ΠΈΡΡ</button> <button id="button_cancel">ΠΡΠΌΠ΅Π½Π°</button> </div> </div> My script
/*Π‘ΠΊΡΠΈΠΏΡ ΡΠ΄Π°Π»Π΅Π½ΠΈΡ Π·Π°Π΄Π°ΡΠΈ*/ $(".delete").click(function () { // ΠΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΠΌ Π½ΠΎΠΌΠ΅Ρ ΡΡΡΠΎΠΊΠΈ ΠΏΠΎ Π½Π°ΠΆΠ°ΡΠΎΠΌΡ p var num = $(this).parent().parent().index(); // ΠΠ΅Π»Π°Π΅ΠΌ ΠΌΠΎΠ΄Π°Π»ΡΠ½ΠΎΠ΅ ΠΎΠΊΠ½ΠΎ Π²ΠΈΠ΄ΠΈΠΌΡΠΌ $(".modal_delete").css("display", "flex"); // ΠΠ½ΠΎΠΏΠΊΠ° ΡΠ΄Π°Π»Π΅Π½ΠΈΡ $("#button_delete").click(function () { // Π‘ΠΊΡΡΠ²Π°Π΅ΠΌ ΠΌΠΎΠ΄Π°Π»ΡΠ½ΠΎΠ΅ ΠΎΠΊΠ½ΠΎ $(".modal_delete").hide(); // Π£Π΄Π°Π»ΡΠ΅ΠΌ ΡΡΡΠΎΠΊΡ $("#table_main").children().children().eq(num).remove(); // (1) }); }); What is the problem ?
The first time the function works fine. But with each subsequent call it deletes several lines already. Through the browser console revealed that the line of code (*) works several times: the first time it is called once, the second time - twice, the third time - three times, etc. You can see that the value of the variable num changes every time.
For example, if I click on "Delete" lines 1 - 3 - 5, then the second call to the num function will be 3 when the line (1) is triggered with num 3, then the value of num will change to the previous one - 1, and the line (1) will work again. In the third call, the values ββof num will change in this order: 5 - 3 - 1 (that is, the reverse).
Why does num change its meaning? I see this behavior of variables for the first time.
Question : how to ensure the operation of the string (*) once? How to make the num value the only one?
PS Alternative solutions to the problem are also being taken.