Trigger a click event on an inner element

前端 未结 14 622
后悔当初
后悔当初 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: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()
       }
    }
    

提交回复
热议问题