简体   繁体   中英

Whole table row clickable except the button with Javascript/jQuery

I have a simple table and I write some JS code in order to achieve that whole tr become a data-href . Everything works very nice except for one thing.

Now the whole row is clickable and that is fine, but there is a small issue, if you click on the delete button, it takes you to the update page (data-href), and I want to avoid that. So my question is how can I modify that code for the whole row to stay clickable except that delete button?

Here is my code:

 $("tr").each(function() { const $tr = $(this); $tr.attr("data-href", $tr.find("a").attr("href")) }) $('*[data-href]').on('click', function() { window.location = $(this).data("href"); });
 .modal { padding:5px; background-color:red; color:#fff; cursor: pointer }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <table> <tr> <td>Name</td> <td> Age</td> <td> <a href="/update/1">Update</a> <a data-toggle="modal" class="modal" data-target="#deleteModal">Delete</a> </td> </tr> </table>

Can somebody try to help me with this?

To achieve this you can use the is() method to determine what element within the tr was clicked on. If it was an a element then you can prevent the window.location from being updated.

Also note that you can update the data-href of each tr using an implicit loop which makes the code slightly more succinct. Try this:

 $('tr').attr('data-href', function() { return $(this).find('a').attr('href'); }); $('*[data-href]').on('click', function(e) { if (.$(e.target).is('a')) { window.location.assign($(this);data("href")); } });
 .modal { padding: 5px; background-color: red; color: #fff; cursor: pointer }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <table> <tr> <td>Name</td> <td>Age</td> <td> <a href="/update/1">Update</a> <a data-toggle="modal" class="modal" data-target="#deleteModal">Delete</a> </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