javascript - this.name 在 javascript 中返回 undefined

标签 javascript element onload

我正在尝试远程创建一个 onclick对于每个 <div> (以节省打字时间)。

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

每个 <div> 的名称是"flyingsheep" - 此值由 <div name="flyingsheep"> 设置.

当我点击 <div> , iframe "game"带我到网页"/games/undefined" .

最佳答案

这会起作用。问题已得到纠正。

只需使用: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;} 
        }
}

关于javascript - this.name 在 javascript 中返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5528276/

相关文章:

JavaScript 服务器元素 onclick 事件

javascript - 如何覆盖onLoad?

javascript - body onload 执行时是否有可能留下未读代码?

XSLT根据父子元素的值删除子元素

list - 如何使用列表删除函数中的重复元素?

javascript - XmlHttpRequest.onload 在 Edge 浏览器中不起作用

javascript - 如何访问axios实例的baseURL

javascript - 如何忽略 javascript 中的 $1 替换反向引用

javascript - jsTree搜索文本框不出现

javascript - HTML 菜单设置父项类(如果子项有类)