Detecting an item clicked on

I have a table with trwhere you can click. These trmay contain a.

  <tr id="12" href="/guestbook/edit?id=12">
    <td class="main">
       <strong>Remi</strong>
       <a href="mailto:xxx@xxx">xxx@xxx</a>
    </td>
    <td class="date">05-11-2010 11:34</td>
    <td class="number">ip</td>
  </tr>

This is jquery code to detect tr click

$('table tr[href]').click(function(e){
   document.location.href = $(this).attr('href');
});

When I click on an email address, for example, my email client opens first (which is good), and then the page editing (which is bad) is loaded. Is it possible to detect the element that I clicked on? If it is A or TR?

+3
source share
2 answers

You can check the .targetevents and see what it is .nodeName, like this:

$('table tr[href]').click(function(e){
   if(e.target.nodeName == 'A') return;
   document.location.href = $(this).attr('href');
});

Since @ Hannes says in the comments, it is better to use the data attribute here, for example:

<tr id="12" data-href="/guestbook/edit?id=12">

Then in your code:

$(this).attr('data-href');

, jQuery 1.4.3 +:

$(this).data('href');
+10

, , , onclick. , :

$('tr[href] a').click(function(e) {
    $(e.target).closest('tr[href]').trigger('click');
    return false;  // stop event propagation (email client won't be called)
});

, .

0

Source: https://habr.com/ru/post/1774047/


All Articles