Trigger a click event on an inner element

前端 未结 14 518
后悔当初
后悔当初 2020-12-29 07:53

A row in a table where each first cell contains a link needs to be clicked and open a url.

相关标签:
14条回答
  • 2020-12-29 08:33

    Try

    $(".fancybox").parent('td').parent('tr').bind('click',function(e) {
        e.stopPropagation();
        $(this).find("a").trigger('click');
    });
    
    0 讨论(0)
  • 2020-12-29 08:39

    This worked well:

    $("table tr").click(function(e) {
        var $link = $(this).find("a");
    
        if (e.target === $link[0]) return false;
    
        $link.trigger('click');
        return false;
    });
    

    EDIT:

    Why most solutions don't work — they fail, because when the link was clicked, the immediate handler attached runs. The event then bubbles to see if a handler was attached to a table cell, row, etc.

    When you suggest triggering a click you cause the recursion: the link was clicked → fancybox → bubbles → aha! table row → trigger the link click → the link was clicked…

    When you suggest to stop propagation, please note that event stops bubbling to parent elements, so a click handler attached to body will not be executed.

    Why the code above works — we check if the event bubbled from a link. If true, we simply return and stop further propagation.


    See the updated fiddle: http://jsfiddle.net/F5aMb/28/

    0 讨论(0)
提交回复
热议问题