简体   繁体   English

this.name 在 javascript 中返回 undefined

[英]this.name returns undefined in javascript

I am trying to remotely create an onclick for each <div> (to save typing time).我正在尝试为每个<div>远程创建一个onclick (以节省打字时间)。

Here is the window.onload() function:这是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 <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 "game"将我带到网页"/games/undefined"

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

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. <div name="flyingsheep">不是传统的,它是无效的。 There is no name attribute for div elements. div 元素没有name属性

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.如果当您尝试设置divel.length.onmouseover时 JS 抛出错误,我不会感到惊讶——不要在类似对象的数组上使用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函数。

在 jquery 中,您可以改为使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM