Trigger a click event on an inner element

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

    My usecase was to trigger a click when a -element was clicked. Checking the type of the target element solves the recursive call problem.

    $('#table tbody td').click(function(e){
        if ($(e.target).is('td')) {
            $(this).find('input').trigger('click');
        }
    });
    
    0 讨论(0)
  • 2020-12-29 08:17

    In order to compensate for the bubbling, you need to detect the target of the event and not click on the link more than once. Also, jQuery's "trigger" function won't work for plain links, so you need a specialized click function.

    you can try it out at: http://jsfiddle.net/F5aMb/27/

    $("table tr").each(function(i, tr){
        $(tr).bind('click',function(e) {
            var target = $(e.target);
            if( !target.is("a") ) {
                clickLink($(this).find("a")[0]);
            }
        })
    });
    
    
    function clickLink(element) {
       if (document.createEvent) {
           // dispatch for firefox + others
           var evt = document.createEvent("MouseEvents");
           evt.initEvent("click", true, true ); // event type,bubbling,cancelable
           return !element.dispatchEvent(evt);
       } else {
           //IE
           element.click()
       }
    }
    
    0 讨论(0)
  • 2020-12-29 08:17
    $('a.fancybox').click(function(evt){evt.stopPropagation())});
    
    $('table tr:has[.fancybox]').click(function(evt){
    $(this).find('.fancybox').trigger('click')
    })
    
    0 讨论(0)
  • 2020-12-29 08:19

    I was able to do it by giving each link a unique ID and then using jQuery to set the click event of that unique ID to redirect the window to the appropriate page.

    Here is my working example: http://jsfiddle.net/MarkKramer/F5aMb/2/

    And here is the code:

    $('#link1').click(function(){
        // do whatever I want here, then redirect
        window.location.href = "detail.aspx?CID=67525";
    });
    $('#link2').click(function(){
        // do whatever I want here, then redirect
        window.location.href = "detail.aspx?CID=17522";
    });
    
    $("table tr").click(function(e) {
        e.stopImmediatePropagation();
        $(this).find("a").trigger('click');
    });
    
    0 讨论(0)
  • 2020-12-29 08:20

    try

    $('table tr').click(function() {
      var href = $(this).find("a").attr("href");
        if(href) {
           window.location = href;
        }
    });
    
    0 讨论(0)
  • 2020-12-29 08:20

    It may be that I misunderstood your question, but doesn't this do what you need:

    $("table tr").click(function(e) {
        e.stopImmediatePropagation();
        if (! $(e.target).is('a')) {
            $(this).find("a").trigger('click');
        }
    });
    
    0 讨论(0)
提交回复
热议问题