javascript appendChild 没有工作并给我一个 [object] 结果
javascript appendChild did not work and give me an [obect] result
运行 下面的代码,我得到的结果是这样的:
[object HTMLHeadingElement]
[object HTMLHeadingElement]
[object HTMLHeadingElement]
[object HTMLHeadingElement]
但它应该有一些 ul
列表的结果。我不知道我哪里错了。我错过了什么?
function textContent(ele,value){
var content = ele.textContent;//check if textContent is defined
if(value === undefined){//no value passed, so return current text
if(content !== undefined) return content;
else return ele.innerText;
}else{//a value is passed, so set text
if(content !== undefined) ele.textContent = value;
else ele.innerText = value;
}
}
(function(){
var titles = document.querySelectorAll('.docHomeDetails h3');
var sideList = document.getElementsByClassName('sideList')[0];
var ul = document.querySelectorAll('.sideList ul')[0];
window.onload = function(){
for(var i = 0; i< titles.length; i++){
var li = document.createElement('li');
textContent(li, titles[i]);//setting plain text into li element
ul.appendChild(li);
}
}
}());
错误在这里:
textContent(li, titles[i]);//setting plain text into li element
您尝试分配元素本身而不是其中的文本。应该是:
textContent(li, titles[i].innerHTML);
我的fiddle.
运行 下面的代码,我得到的结果是这样的:
[object HTMLHeadingElement]
[object HTMLHeadingElement]
[object HTMLHeadingElement]
[object HTMLHeadingElement]
但它应该有一些 ul
列表的结果。我不知道我哪里错了。我错过了什么?
function textContent(ele,value){
var content = ele.textContent;//check if textContent is defined
if(value === undefined){//no value passed, so return current text
if(content !== undefined) return content;
else return ele.innerText;
}else{//a value is passed, so set text
if(content !== undefined) ele.textContent = value;
else ele.innerText = value;
}
}
(function(){
var titles = document.querySelectorAll('.docHomeDetails h3');
var sideList = document.getElementsByClassName('sideList')[0];
var ul = document.querySelectorAll('.sideList ul')[0];
window.onload = function(){
for(var i = 0; i< titles.length; i++){
var li = document.createElement('li');
textContent(li, titles[i]);//setting plain text into li element
ul.appendChild(li);
}
}
}());
错误在这里:
textContent(li, titles[i]);//setting plain text into li element
您尝试分配元素本身而不是其中的文本。应该是:
textContent(li, titles[i].innerHTML);
我的fiddle.