this.name 在 javascript 中返回 undefined
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5528276/
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
this.name returns undefined in javascript
提问by drnessie
I am trying to remotely create an onclick for each div (to save typing time). Here is the window.onload function;
我正在尝试为每个 div 远程创建一个 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; };
}
}
The name of every div is "flyingsheep" - this value was set by the traditional < div name="flyingsheep" >
每个div的名字都是“flyingsheep”——这个值是由传统的<div name="flyingsheep">设置的
When I click the div, the iframe "game" takes me to the webpage "/games/undefined"
当我单击 div 时,iframe“游戏”将我带到网页“/games/undefined”
Thanks in advance.
提前致谢。
(Tested in Google Chrome and Fennec (not the most conventional browsers, I know))
(在 Google Chrome 和 Fennec 中测试(我知道不是最传统的浏览器))
回答by Farzin Zaker
This will work. the problem is corrected.
这将起作用。问题得到纠正。
just use : this.attributes["name"].value
只需使用: this.attributes["name"].value
window.onload = function() {
divel = document.getElementsByTagName('div');
for(var el in divel){
window.alert(divel[el].name);
divel[el].onmouseover = function(){ this.style.textDecoration = "underline"; };
divel[el].onmouseout = function(){ this.style.textDecoration = "none"; };
divel[el].onclick = function(){document.getElementById('game').src = this.attributes["name"].value;}
}
}
回答by Tapper
回答by Quentin
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 no name
attributefor div elements.
<div name="flyingsheep">
不是传统的,它是无效的。有没有name
属性的div元素。
I wouldn't be surprised if the JS was throwing an error when you try to set divel.length.onmouseover
— don't use for ( foo in bar )
on array like objects, use a normal counter.
如果在您尝试设置时 JS 抛出错误,我不会感到惊讶divel.length.onmouseover
- 不要for ( foo in bar )
在像对象这样的数组上使用,使用普通计数器。
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.
我最好的理论是,您拥有的div
元素比您关心的元素多,并且单击其中一个元素(没有名称属性的元素),可能包含您要单击的元素)触发 JS功能。