繁体   English   中英

未捕获的类型错误:无法读取未定义的属性“getAttribute”

[英]Uncaught TypeError: Cannot read property 'getAttribute' of undefined

我正在使用“DOM Scripting”这本书,并按照第 8 章中的代码尝试创建定义列表,但它没有显示出来。 Chrome 控制台显示以下错误:

未捕获的类型错误:无法读取 displayAbbreviations (displayAbbreviations.js:13) 处未定义的属性“getAttribute”

我的代码如下。 谁能帮我找出哪里出了问题?非常感谢!

function displayAbbreviations(){
    if(!document.getElementsByTagName) return false;
    if(!document.createElement) return false;
    if(!document.createTextNode) return false; 

    //get all the abbreviations
    var abbreviations=document.getElementsByTagName("abbr");
    if (abbreviations.length<1) return false;
    var defs = new Array();
    //loop through the abbreviations
    for (var i=0; i<abbreviations.length;i++);{
        var current_abbr=abbreviations[i];
        var definition=current_abbr.getAttribute("title");
        var key=current_abbr.lastChild.nodeValue;
        defs[key]=definition; 
    }

//Create the definition list
var dlist=document.createElement("dl");

// loop through the definitions
for (key in defs){
    var definition=defs[key];
//create the definition title
    var dtitle=document.createElement("dt");
    var dtitle_text=document.createTextNode(key);
    dtitle.appendChild(dtitle_text);
//create the definition description
    var ddesc=document.createElement("dd");
    var ddesc_text=document.createTextNode(definition);
    ddesc.appendChild(ddesc_text);
//add them to the definition list
    dlist.appendChild(dtitle);
    dlist.appendChild(ddesc);

}

//create a headline
var header=document.createElement("h2");
var header_text=document.createTextNode("Abbreviations");
header.appendChild(header_text);
// add the headline to the body
document.body.appendChild(header);
//add the definition list to the body
document.body.appendChild(dlist);
}

addLoadEvent(displayAbbreviations);

OP 的问题是他错误地在 for 循环中放置了一个 break( ; ) 。 还有其他一些应该解决的错误,比如defs变量最初被声明为一个数组。 虽然它在后续代码中像对象一样使用

更正的代码

    var defs = {};
    //loop through the abbreviations
    for (var i=0; i<abbreviations.length;i++){
        var current_abbr=abbreviations[i];
        var definition=current_abbr.getAttribute("title");
        var key=current_abbr.lastChild.nodeValue;
        defs[key]=definition; 
    }

暂无
暂无

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

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