我正在上 Ajax 类(class),这个非常简单的脚本抛出了一个我不明白的错误。我一直收到未捕获的类型错误,说 appendChild 方法不是函数。
我正在使用的函数旨在在单击链接时将文本文件的内容异步加载到“p”标记中。
我对 javascript 有点陌生,所以它可能是我错过的一些简单的东西,如果能帮助我理解我做错了什么,我将不胜感激。
(function(){
var link = document.getElementsByTagName('a')[0];
link.onclick = function(){
//create xhr object
var xhr = new XMLHttpRequest();
// handle the "onreadystatechange" event
/*
xhr.readysState property values
0 = Uninitialized
1 = Loading
2 = Loaded
3 = Interactive - server is sending a response
4 = Complete
*/
xhr.onreadystatechange = function() {
if ( (xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304) ) {
xhr.responseText;
var body = document.getElementsByTagName('body')[0];
var p = document.getElementsByTagName('p');
var pText = document.createTextNode(xhr.responseText);
console.log(p);
console.log(pText);
p.appendChild(pText);
body.appendChild(p);
}
};
// open the request
/* arguments:
1. type of request a (GET or POST)
2. path
3. asynchronaus request? (true || false)*/
xhr.open('GET', 'files/ajax.txt', true);
// send the request
xhr.send(null)
return false; // disable default behavior of link
};
})();
我创建了一个 jsFiddle 来显示我的代码: http://jsfiddle.net/scottm1164/656edjsf/
最佳答案
getElementsByTagName返回一个 NodeList
。因此,您必须访问具有类似索引的单个项目
var p = document.getElementsByTagName('p')[0];
它给你的原因
p.appendChild is not a function
是因为appendChild
不是NodeList
类型的函数
关于javascript - 未捕获的 TypeError : p. appendChild 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30443718/