将单个事件附加到存储在数组中的多个元素,原生 JS
每个人都在建议一些框架,但我想知道如何在原生 JavaScript 中完成它。我已经尝试过这段代码和其他一些东西,没有效果。似乎我不知道一些基本的概念。任何帮助将不胜感激。
window.onload = function() {
var trCurrent
var main = document.getElementById('main');
var tr = main.getElementsByTagName('tr');
function hl() {
trCurrent.setAttribute('class', 'highlight');
};
for (var x = 0; x < tr.lenght; x++) {
trCurrent = tr[x];
trCurrent.addEventListener ('mousedown', hl, false);
}
};
Everyone is suggesting some framework, but I'd like to know how it can be done in native JavaScript. I've tried this code and some other things, no effect. Seems that I'm unaware of some basic underlying concept. Any help would be appreciated.
window.onload = function() {
var trCurrent
var main = document.getElementById('main');
var tr = main.getElementsByTagName('tr');
function hl() {
trCurrent.setAttribute('class', 'highlight');
};
for (var x = 0; x < tr.lenght; x++) {
trCurrent = tr[x];
trCurrent.addEventListener ('mousedown', hl, false);
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
函数h1
中将trCurrent
更改为this
,因为trCurrent
指向最后定义的TR元素(trCurrent = tr[x]
表示高x
)。.length
而不是.lenght
。最终代码:
如果您想使用在循环期间可能发生变化的变量,则需要将主体包装在(匿名)函数中:
trCurrent
tothis
at yourfunction h1
, becaysetrCurrent
points to the last defined TR element (trCurrent = tr[x]
for a highx
)..length
instead of.lenght
.Final code:
If you want to use an variable which is subject to change during a loop, it's required to wrap the body in an (anonymous) function: