Difference between .click() and actually clicking a button? (javascript/jQuery)

前端 未结 4 1685
鱼传尺愫
鱼传尺愫 2020-11-30 04:00

I\'m trying to figure out this weird issue I\'ve been having, and the root cause is the difference between a live click and triggering .click()

4条回答
  •  旧时难觅i
    2020-11-30 04:36

    I use this function to truly mimic a mouse click:

    function clickLink(link) {
        var cancelled = false;
    
        if (document.createEvent) {
            var event = document.createEvent("MouseEvents");
            event.initMouseEvent("click", true, true, window,
                0, 0, 0, 0, 0,
                false, false, false, false,
                0, null);
            cancelled = !link.dispatchEvent(event);
        }
        else if (link.fireEvent) {
            cancelled = !link.fireEvent("onclick");
        }
    }
    

提交回复
热议问题