jQuery .click() works on every browser but Safari

让人想犯罪 __ 提交于 2019-11-27 19:00:21
var a = $('.shell a')[0];
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
a.dispatchEvent(evObj);

See http://www.howtocreate.co.uk/tutorials/javascript/domevents (search for "Manually firing events").

Trevor Dixon's answer does fix Safari, but breaks in even the latest Firefox:

TypeError: Not enough arguments to MouseEvent.initMouseEvent

The best way to support Safari—without breaking Firefox—would be using initEvent instead of initMouseEvent like so:

var element = document.getElementById('your_id_here');
if(element.click)
    element.click();
else if(document.createEvent)
{
    var eventObj = document.createEvent('MouseEvents');
    eventObj.initEvent('click',true,true);
    element.dispatchEvent(eventObj);
}

To update for 2016, MouseEvent should be used instead of initMouseEvent which is deprecated:

var eventObj = new MouseEvent("click", {
    bubbles: true,
    cancelable: true
});
element.dispatchEvent(eventObj);

$('.shell a')[0] gets a DOM object out of the jQuery object. That DOM object only has DOM methods (not jQuery methods) and there is no industry standard .click() method on an <a> element until HTML5 and it is not yet implemented in every browser - thus you will see incomplete implementation across difference browsers.

You have a couple choices. The first option gets a jQuery object and uses the .click() method on the jQuery object. This will only work reliably if you are triggering jQuery click handlers, not if you just want the default click for the <a> tag.

function writeAndClickLink(url) {

    $('.shell').html('<a href="' + url + '"></a>');
    $('.shell a').eq(0).click();
}

Or, if clicking the URL is just going to go to a new web page, don't even bother modifying the DOM and just set window.location as there is no point in modifying the DOM at all if you're just going to a new web page:

function writeAndClickLink(url) {
    window.location = url;    
}

$('.shell a')[0] returns the native DOM element which dosn't have jQuery methods bound to it

Remove the "[0]" to keep the jQuery object in order to use jQuery methods

 $('.shell a').click()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!