this.name在javascript中返回undefined

drn*_*sie 6 javascript element onload

我正在尝试为每个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; };
            }
}
Run Code Online (Sandbox Code Playgroud)

每个div的名称都是"flyingsheep" - 这个值是由传统的<div name ="flyingsheep">设置的

当我点击div时,iframe"游戏"将我带到网页"/ games/undefined"

提前致谢.

(在谷歌浏览器和Fennec中测试过(不是最传统的浏览器,我知道))

Far*_*ker 12

这会奏效.问题得到纠正.

只需使用: 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;} 
        }
}
Run Code Online (Sandbox Code Playgroud)