javascript 如何在javascript中向div添加onclick函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11659564/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:56:04  来源:igfitidea点击:

How do I add an onclick function to a div in javascript?

javascript

提问by Sir

I have a piece of javascript is meant to add an onclick event to a div.

我有一段 javascript 是为了向 div 添加一个 onclick 事件。

The div looks like this:

div 看起来像这样:

<div id="deck0" class="deck"></div>

And my javascript has:

我的 javascript 有:

var i = 1;
document.getElementById('deck0').SetAttribute("onclick", "begin("+i+")");   

But I get this error:

但我收到此错误:

Uncaught TypeError: Object #<HTMLDivElement> has no method 'SetAttribute' 

Am I doing it right, or is what I am trying to achieve not possible?

我做得对吗,或者我想要实现的目标是不可能的?

回答by RobG

Don't use setAttributeto set listeners, not all browsers allow that. Much better to either set the property directly:

不要使用setAttribute来设置侦听器,并非所有浏览器都允许这样做。直接设置属性要好得多:

document.getElementById('deck0').onclick = begin;

or use addEventListener:

或使用addEventListener

document.getElementById('deck0').addEventListener('click', begin, false);

If you need to pass a parameter, then:

如果需要传递参数,则:

document.getElementById('deck0').onclick = function() {begin(i);};

similarly for addEventListener.

addEventListener类似。

Note that earlier versions of IE don't support addEventListenerso you will need a cross–browser function to feature test for support. Where lacking, test for attachEventand fall back to the direct property method. Search for "addEvent" functions, there are plenty of examples.

请注意,早期版本的 IE 不支持addEventListener,因此您需要一个跨浏览器的功能来进行功能测试以获得支持。如果缺少,请测试attachEvent并回退到直接属性方法。搜索“addEvent”函数,有很多例子。

回答by SLaks

Javascript is case-sensitive.
That should be setAttribute.

Javascript 区分大小写。
那应该是setAttribute

回答by Bergi

Javascript is case-sensitive, you'd need to write itlowercase.

JavaScript是大小写敏感的,你需要写小写。

Apart from that, to set event listenersno attributesshould be used. This would need a string to be evaluated each time - you can do better from a script. Instead, assign a function to the onclickproperty:

除此之外,要设置事件侦听器,不应使用任何属性。这将需要每次评估一个字符串 - 您可以从脚本中做得更好。相反,为onclick属性分配一个函数:

document.getElementById('deck0').onclick = function(event) {
    begin(1);
};

Advanced event registrationwould be even better, but is more complex because Microsoft lacks supporting the standard.

高级事件注册会更好,但更复杂,因为 Microsoft 缺乏对标准的支持。

回答by Dalmas

There are other ways to associate a function to the onclickevent :

还有其他方法可以将函数与onclick事件相关联:

function deck0_onclick() {
    begin(i);
}

document.getElementById('deck0').onclick = deck0_onclick;

Or directly :

或直接:

document.getElementById('deck0').onclick = function() {begin(i);}