this.name returns undefined in javascript

不想你离开。 提交于 2019-12-04 05:22:45

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;} 
        }
}

In jquery you could instead use:

$(this).attr("name");

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!