Javascript 如何使用javascript设置onclick?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13637133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set onclick with javascript?
提问by mjr
I am trying to set the onclick event using javascript. The following code works:
我正在尝试使用 javascript 设置 onclick 事件。以下代码有效:
var link = document.createElement('a');
link.setAttribute('href', "#");
link.setAttribute('onclick', "alert('click')");
I then use appendChild to add link to the rest of the document.
然后我使用 appendChild 添加指向文档其余部分的链接。
But I obviously would like a more complicated callback than alert, so I tried this:
但我显然想要一个比警报更复杂的回调,所以我尝试了这个:
link.onclick = function() {alert('clicked');};
and this:
和这个:
link.onclick = (function() {alert('clicked');});
But that does nothing. When I click the link, nothing happens. I have testing using chrome and browsing the DOM object shows me for that element that the onclick attribute is NULL.
但这没有任何作用。当我点击链接时,没有任何反应。我使用 chrome 进行了测试,浏览 DOM 对象显示该元素的 onclick 属性为 NULL。
Why am I not able to pass a function into onclick?
为什么我无法将函数传递给 onclick?
EDIT:
编辑:
I tried using addEventListener as suggested below with the same results. The DOM for the link shows onclick as null.
我尝试按照下面的建议使用 addEventListener 并得到相同的结果。链接的 DOM 将 onclick 显示为 null。
My problem may be that the DOM for this element might not have been fully built yet. At this point the page has been loaded and the user clicks a button. The button executes javascript that builds up a new div that it appends to the page by calling document.body.appendChild. This link is a member of the new div. If this is my problem, how do I work around it?
我的问题可能是该元素的 DOM 可能尚未完全构建。此时页面已经加载完毕,用户点击了一个按钮。该按钮执行 javascript,它通过调用 document.body.appendChild 构建一个新的 div 并将其附加到页面。这个链接是新div的成员。如果这是我的问题,我该如何解决?
采纳答案by Miltos Kokkonidis
I have been unable to reproduce the problem. Contrary to the OP's findings, the line below works fine on the latest versions of IE, FF, Opera, Chrome and Safari.
我一直无法重现该问题。与 OP 的调查结果相反,下面的行在最新版本的 IE、FF、Opera、Chrome 和 Safari 上运行良好。
link.onclick = function() {alert('clicked');};
You can visit this jsFiddle to test on your own browser:
您可以访问这个 jsFiddle 在您自己的浏览器上进行测试:
Assuning we have this in the html page:
Assuning 我们在 html 页面中有这个:
<div id="x"></div>
The following code works fine on the browsers I have tried it with:
以下代码在我尝试过的浏览器上运行良好:
var link = document.createElement('a');
link.appendChild(document.createTextNode("Hi"));
link.setAttribute('href', "#");
link.onclick= function() {link.appendChild(document.createTextNode("Clicked"));}
document.getElementById("x").appendChild(link);
If there is a browser compatibility issue, using jQuery should solve it and make code much much more concise:
如果存在浏览器兼容性问题,使用 jQuery 应该可以解决它并使代码更加简洁:
var $link = $("<a>").html("Hi").attr("href","#").click(function (){$link.html("Clicked")})
$("#x").html($link)
If brevity is not a strong enough argument for using jQuery, browser compatibility should be ... and vise versa :-)
如果简洁对于使用 jQuery 来说不够有力,那么浏览器兼容性应该是……反之亦然 :-)
NOTE: I am not using alert() in the code because jsFiddle does not seem to like it :-(
注意:我没有在代码中使用 alert() 因为 jsFiddle 似乎不喜欢它:-(
回答by JCOC611
You can add a DOM even listener with addEventListener(...), as David said. I've included attachEventfor compatibility with IE.
addEventListener(...)正如大卫所说,您可以添加一个 DOM 甚至侦听器。我已经包含attachEvent了与 IE 的兼容性。
var link = document.createElement('a');
link.setAttribute('href', "#");
if(link.addEventListener){
link.addEventListener('click', function(){
alert('clicked');
});
}else if(link.attachEvent){
link.attachEvent('onclick', function(){
alert('clicked');
});
}
回答by Marios Fakiolas
Use sth like this if you like:
如果你愿意,可以这样使用:
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
回答by bfavaretto
Setting an attribute doesn't look right. The simplest way is just this:
设置属性看起来不正确。最简单的方法就是这样:
link.onclick = function() {
alert('click');
};
But using addEventListeneras JCOC611 suggested is more flexible, as it allows you to bind multiple event handlers to the same element. Keep in mind you might need a fallback to attachEventfor compatibility with older Internet Explorer versions.
但是使用addEventListenerJCOC611 建议更灵活,因为它允许您将多个事件处理程序绑定到同一个元素。请记住,attachEvent为了与较旧的 Internet Explorer 版本兼容,您可能需要回退。

