this.name returns undefined in javascript

2019-04-08 07:53发布

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 the traditional < div name="flyingsheep" >

When I click the div, the iframe "game" takes me to the webpage "/games/undefined"

Thanks in advance.

(Tested in Google Chrome and Fennec (not the most conventional browsers, I know))

3条回答
别忘想泡老子
2楼-- · 2019-04-08 08:17

This will work. the problem is corrected.

just use : 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;} 
        }
}
查看更多
我命由我不由天
3楼-- · 2019-04-08 08:19

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 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 use for ( 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.

查看更多
一夜七次
4楼-- · 2019-04-08 08:21

In jquery you could instead use:

$(this).attr("name");
查看更多
登录 后发表回答