admin管理员组文章数量:1312718
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.
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.
- 2 If you are really worried about cross-browser patability, then I'd suggest using a JS library like jQuery. – gen_Eric Commented Oct 30, 2012 at 14:52
-
Do you know what could replace the
.click()
method in jQuery? – don Commented Oct 30, 2012 at 14:58 -
2
The
.click
method :-) – gen_Eric Commented Oct 30, 2012 at 15:02 -
Are you talking about
.onclick()
? This is native javascript to bind a click event and is supported in all major browsers. – Andrew Klatzke Commented Jan 22, 2013 at 20:55
3 Answers
Reset to default 4The 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.
According to MDN, HTMLElement.click()
is supported by Chrome 20+, Firefox 5+ and Safari 6+. But that might be inaccurate.
I had this problem and used it instead of $('#selector').click(function(){});
, used (document).on('click','#selector',function(){});
本文标签: javascriptclick() methodbrowser supportStack Overflow
版权声明:本文标题:javascript - .click() method, browser support - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741894088a2403473.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论