Trigger a click event on an inner element

前端 未结 14 634
后悔当初
后悔当初 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:29

    Try this:

    $("table tr a").bind('click', function(e) {
         e.preventDefault();
         window.open($(this).attr('href'));
         return false;
    });
    
    $("table tr").bind('click', function(e) {
         $(this).find("a").trigger('click');
     });
    

    I found what went wrong.

    In your code,

    $("table tr").bind('click',function(e) {
    e.stopPropagation();
    $(this).find("a").trigger('click');//This line again triggers a click event binded on the tr ELEMENT which contains the 'a' ELEMENT. So it goes into a infinite loop.
    });
    

    Update:

    This will do.

    $("table tr").bind('click', function(e) {
       window.location.href = $(this).find("a.fancybox").attr('href');
    });
    

    $(this).find("a").trigger('click'); is actually not triggering the default anchor tag behavior. It just tries to trigger a click event if a click event is already bound to that element explicitly.

提交回复
热议问题