简体   繁体   English

如何用JavaScript设置onClick?

[英]How to set onClick with JavaScript?

I am trying to set the onclick event using javascript.我正在尝试使用 javascript 设置 onclick 事件。 The following code works:以下代码有效:

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.我尝试按照下面的建议使用 addEventListener,结果相同。 The DOM for the link shows onclick as null.链接的 DOM 将 onclick 显示为 null。

My problem may be that the DOM for this element might not have been fully built yet.我的问题可能是该元素的 DOM 可能尚未完全构建。 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.该按钮执行 javascript,构建一个新的 div,它通过调用 document.body.appendChild 附加到页面。 This link is a member of the new div.此链接是新 div 的成员。 If this is my problem, how do I work around it?如果这是我的问题,我该如何解决?

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 在你自己的浏览器上测试:

http://jsfiddle.net/6MjgB/7/ http://jsfiddle.net/6MjgB/7/

Assuning we have this in the html page:假设我们在 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 似乎不喜欢它:-(

If you're doing this with JavaScript, then use addEventListener() , with addEventListener('click', function(e) {...}) to get the event stored as e .如果您使用 JavaScript 执行此操作,则使用addEventListener()addEventListener('click', function(e) {...})将事件存储为e If you don't pass in the event like this, it will not be accessible (although Chrome appears to be smart enough to figure this out, not all browsers are Chrome).如果你不传入这样的事件,它将无法访问(尽管 Chrome 似乎足够聪明,可以解决这个问题,但并非所有浏览器都是 Chrome)。

Full Working JSBin Demo. 完整的 JSBin 演示。

StackOverflow Demo... StackOverflow 演示...

 document.getElementById('my-link').addEventListener('click', function(e) { console.log('Click happened for: ' + e.target.id); });
 <a href="#" id="my-link">Link</a>

You can add a DOM even listener with addEventListener(...) , as David said.正如大卫所说,您可以使用addEventListener(...)添加 DOM 甚至监听器。 I've included attachEvent for compatibility with IE.为了与 IE 兼容,我包含了attachEvent

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');
   });
}

Setting an attribute doesn't look right.设置属性看起来不正确。 The simplest way is just this:最简单的方法就是这样:

link.onclick = function() {
    alert('click');
};

But using addEventListener as JCOC611 suggested is more flexible, as it allows you to bind multiple event handlers to the same element.但是按照 JCOC611 的建议使用addEventListener更灵活,因为它允许您将多个事件处理程序绑定到同一元素。 Keep in mind you might need a fallback to attachEvent for compatibility with older Internet Explorer versions.请记住,您可能需要回attachEvent以与旧的 Internet Explorer 版本兼容。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM