简体   繁体   English

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

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

I have a piece of javascript is meant to add an onclick event to a div. 我有一段javascript意味着将一个onclick事件添加到div。

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? 我做得对,还是我想要实现的不可能?

Don't use setAttribute to set listeners, not all browsers allow that. 不要使用setAttribute设置监听器,并非所有浏览器都允许。 Much better to either set the property directly: 要么直接设置属性要好得多:

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 addEventListener so you will need a cross–browser function to feature test for support. 请注意,早期版本的IE不支持addEventListener,因此您需要一个跨浏览器功能来进行支持测试。 Where lacking, test for attachEvent and fall back to the direct property method. 缺少的地方,测试attachEvent并回退到direct属性方法。 Search for "addEvent" functions, there are plenty of examples. 搜索“addEvent”函数,有很多例子。

Javascript is case-sensitive. Javascript区分大小写。
That should be setAttribute . 那应该是setAttribute

Javascript is case-sensitive, you'd need to write it lowercase. Javascript区分大小写,您需要将其写小写。

Apart from that, to set event listeners no attributes should 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 onclick property : 相反,为onclick属性分配一个函数:

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

Advanced event registration would be even better, but is more complex because Microsoft lacks supporting the standard. 高级事件注册会更好,但更复杂,因为Microsoft缺乏支持标准。

There are other ways to associate a function to the onclick event : 还有其他方法可以将函数与onclick事件相关联:

function deck0_onclick() {
    begin(i);
}

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

Or directly : 或直接:

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

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

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