Chrome“onclick”事件问题
好的,我正在构建一个应用程序(适用于 Chrome(*不是扩展)),并且页面上有一堆重复的元素。因此,我决定使用循环动态构建这些元素,如下所示:
for(var i = 1; i <= 64; i++){
var elem = document.createElement('div');
elem.id = "element"+i;
elem.onclick = "doSomething()"
$("parentElement").appendChild(elem);
}
当它尝试将我的函数附加到 onclick 事件时,就会出现问题。当我查看该元素时,它没有 onclick 属性...即使我单步执行,我也可以到达该行:
elem.onclick = "doSomething()"
然后我再次单步,什么也没有...到目前为止,我已经尝试过带引号和不带引号以及 .onclick和.onClick...
提前谢谢您!
Okay so I am building an application (for Chrome (*not extension)) and have a bunch of repeated elements on the page. So I decided to build these elements dynamically using a loop, like so:
for(var i = 1; i <= 64; i++){
var elem = document.createElement('div');
elem.id = "element"+i;
elem.onclick = "doSomething()"
$("parentElement").appendChild(elem);
}
My issue occurs when it tries to attach my function to the onclick event. When I look at the element there is no onclick attribute on it... Even when I step through I can get to the line:
elem.onclick = "doSomething()"
Then I step again and nothing... So far I have tried with and without quotes and both .onclick and .onClick...
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该始终传递函数本身,而不是任何类型的字符串。
这会将
doSomething
设置为点击处理程序。eval
,这很慢并且可能不安全(后者在这里不适用)。onclick
时才需要字符串。You should pass the function itself at all times, not a string of any kind.
This will set
doSomething
as the click handler.eval
internally, which is slow and possibly unsafe (the latter does not apply here).onclick
through HTML.“addEventListener”是一种更好的方法(如果您想稍后取消绑定/绑定更多事件)。此外,我建议缓存对父元素的引用,如下所示
根据列表的大小,您可以考虑事件委托:(
类名“clickMe”完全是任意的)
编辑:这两个示例都属于OP 在循环内附加到 DOM 的陷阱。应尽可能避免这种情况,因为接触 DOM 的成本很高。这些示例已更新为创建一个文档片段,该片段被填充然后附加到父元素。这使得在第一个示例中不需要缓存对父级的引用。
"addEventListener" is a better approach (in case you want to unbind later/bind more events). In addition, I would recommend caching a reference to the parent element, like so
Depending on the size of the list, you may consider event delegation:
(the class name "clickMe" is completely arbitrary)
Edit: both of these examples fell into the OP's trap of appending to the DOM within a loop. This should be avoided whenever possible, as touching the DOM is expensive. The examples have been updated to instead create a document fragment which is populated and then appended to the parent element. This makes caching a reference to the parent unnecessary in the first example.