9

我想使用js方法.click()如下:

document.getElementById(id).click();

但由于它的工作原理很重要,我想知道哪些浏览器支持该.click()方法。

4

3 回答 3

4

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.

于 2014-05-06T14:08:05.900 回答
0

我遇到了这个问题并使用它而不是$('#selector').click(function(){}); , used(document).on('click','#selector',function(){});

于 2019-10-24T12:00:56.607 回答
0

根据MDNHTMLElement.click()Chrome 20+、Firefox 5+ 和 Safari 6+ 都支持。但这可能不准确

于 2015-12-08T05:16:14.520 回答