.click() method, browser support

谁说胖子不能爱 提交于 2019-12-18 12:29:40

问题


I'd like to use the js method .click() as follows:

document.getElementById(id).click();

But since it is essential that it works, I was wondering of what browsers support the .click() method has.


回答1:


The only browser I have encountered that does not support .click() is Safari. Safari supports .click() on buttons (e.g. <input type="button" />) but not on other elements such as anchor elements (e.g. <a href="#">Click Me</a>).

For Safari, you have to use a workaround:

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

Using the above function, you can support 90%+ of browsers.

Tested in IE7-10, Firefox, Chrome, Safari.




回答2:


According to MDN, HTMLElement.click() is supported by Chrome 20+, Firefox 5+ and Safari 6+. But that might be inaccurate.




回答3:


I had this problem and used it instead of $('#selector').click(function(){}); , used (document).on('click','#selector',function(){});



来源:https://stackoverflow.com/questions/13141495/click-method-browser-support

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