this.name 在 JavaScript 中返回未定义
我正在尝试为每个
远程创建一个 onclick
(以节省打字时间)。这是 window.onload()
函数:
window.onload = function() {
divel = document.getElementsByTagName('div');
for (var el in divel) {
divel[el].onmouseover = function() {
this.style.textDecoration = "underline";
};
divel[el].onmouseout = function() {
this.style.textDecoration = "none";
};
divel[el].onclick = function() {
document.getElementById('game').src = "/games/" + this.name;
};
}
}
每个
的名称是 "flyingsheep"
- 该值由 <代码>。
当我点击
时,iframe "game"
将我带到网页 "/games/undefined"
。I am trying to remotely create an onclick
for each <div>
(to save typing time).
Here is the window.onload()
function:
window.onload = function() {
divel = document.getElementsByTagName('div');
for (var el in divel) {
divel[el].onmouseover = function() {
this.style.textDecoration = "underline";
};
divel[el].onmouseout = function() {
this.style.textDecoration = "none";
};
divel[el].onclick = function() {
document.getElementById('game').src = "/games/" + this.name;
};
}
}
The name of every <div>
is "flyingsheep"
- this value was set by <div name="flyingsheep">
.
When I click the <div>
, the iframe "game"
takes me to the webpage "/games/undefined"
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这会起作用。问题已得到纠正。
只需使用:
this.attributes["name"].value
This will work. the problem is corrected.
just use :
this.attributes["name"].value
很难确定问题是什么,因为我无法访问您的测试用例,所以我看不到任何错误或尝试调整它以使其工作,但有些问题是:
< ;div name="flyingsheep">
不是传统的,它是无效的。 div 元素没有name
属性 。如果当您尝试设置
divel.length.onmouseover
时 JS 抛出错误,我不会感到惊讶 - 不要在数组上使用for ( foo in bar )
像对象一样,使用普通计数器。我最好的理论是,您拥有比您关心的元素更多的
div
元素,并且单击其中一个(没有 name 属性的元素),可能包含您想要的元素单击)正在触发 JS 函数。It is hard to say what the problem is for sure, as I don't have access to your test case so I can't see any errors or try to tweak it to make t work, but some problems are:
<div name="flyingsheep">
is not traditional, it is invalid. There is noname
attribute for div elements.I wouldn't be surprised if the JS was throwing an error when you try to set
divel.length.onmouseover
— don't usefor ( foo in bar )
on array like objects, use a normal counter.My best theory is that you have more
div
elements then the ones you care about, and it is a click on one of those (one without a name attribute), possibly that contains the one you are aiming to click on) that is firing the JS function.在 jquery 中你可以使用:
In jquery you could instead use: