开发者

jQuery - selectors

How shall I bind onClick action to rows except clickable elements?

For example, I have such table:

...
<tbody>
    <tr>
        <td>
            something
        </td>
        <td>
           <a href="some_url.php">link</a>
        </td>
    </tr>
</tbody>
...

If I use such code: $('tbody > tr').开发者_运维问答click(function(){ alert('clicked'); }); then when I click anything within row (including links) I will get my function executed. But I want it to be executed only if I clicked not on clickable element ("a href" in my example).


Take advantage of event bubbling:

$('tbody > tr').click(function(e) {
    /* do something */
});

$('tbody > tr a[href]').click(function(e) {
    e.stopPropagation();
});

When clicking a link it will work as usual but prevent the click event from bubbling up to the tr so its click handler will not trigger in this case.


I guess you could add a .stopPropagation() to the links themselves:

$('tbody > tr').click(function(){
    alert('clicked');
});
$('tbody > tr a').click(function(e){
    e.stopPropagation(); // Prevents the `click` to bubble to the tr handler
});

Basically, the click event will, per default, "bubble" (propagate) up the DOM tree. I.e., with only the click handler on tbody > tr, a click on the tr will result in click event for these elements (in this order):

  1. The tr
  2. The tbody
  3. The table
  4. ...
  5. The body
  6. (The html? - not sure)

Now, the .stopPropagation() call on the event "Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event." (source), thus binding a dedicated handler to the a elements will catch (and stop) the click event on a elements, but leave the tr handler as before (with the exception that a click on the a elements catches those click events that were handled by the tr handler before.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜