js代码出现dom exception 8,无解...


在书上访了一段代码,发现在插入节点的时候出现dom exception 8(找不到节点)错误。奇怪的是,原代码却不会出现这种错误...
我的代码,报错出现在最后一个语句:desdiv.appendChild("descriptionp");

   
  function disdes(){
  
if(request.readyState == 4){
if(request.status == 200){
var desdiv = document.getElementById("description");
for(var i=desdiv.childNodes.length; i>0; i--){
desdiv.removeChild(desdiv.childNodes[i-1]);
}
alert("fuck");
/* var responsedoc = request.responseXML; */
var description = request.responseXML.getElementsByTagName("description")[0];
var descriptiontext = description.firstChild.nodeValue;
var descriptionp = document.createElement("p");
descriptionp.appendChild(
document.createTextNode("Description: " + descriptiontext)
);
desdiv.appendChild("descriptionp");
}
}
}

原书上代码

   
  function displayDetails() {
  
if (request.readyState == 4) {
if (request.status == 200) {
var detailDiv = document.getElementById("description");

// Remove existing item details (if any)
for (var i=detailDiv.childNodes.length; i>0; i--) {
detailDiv.removeChild(detailDiv.childNodes[i-1]);
}

// Add new item details
var responseDoc = request.responseXML;
var description = responseDoc.getElementsByTagName("description")[0];
var descriptionText = description.firstChild.nodeValue;
var descriptionP = document.createElement("p");
descriptionP.appendChild(
document.createTextNode("Description: " + descriptionText));
detailDiv.appendChild(descriptionP);
var price = responseDoc.getElementsByTagName("price")[0];
var priceText = price.firstChild.nodeValue;
var priceP = document.createElement("p");
priceP.appendChild(
document.createTextNode("Price: $" + priceText));
detailDiv.appendChild(priceP);
var urlP = document.createElement("p");
var list = document.createElement("ul");
var urlElements = responseDoc.getElementsByTagName("url");
for (var i=0; i<urlElements.length; i++) {
var url = urlElements[i].firstChild.nodeValue;
var li = document.createElement("li");
var a = document.createElement("a");
a.setAttribute("href", url);
a.appendChild(document.createTextNode(url));
li.appendChild(a);
list.appendChild(li);
}
urlP.appendChild(list);
detailDiv.appendChild(urlP);
}
}
}

Ajax JavaScript

lalal 12 years, 9 months ago

desdiv.appendChild("descriptionp");
把descriptionp两边的双引号去掉.
desdiv.appendChild(descriptionp);
descriptionp是一个变量,你放在双引号里,变成字符串了

阿卓BIU answered 12 years, 9 months ago

Your Answer