我遇到了一些麻烦,要发现我的代码中有什么问题要删除我列表中的所有孩子:
document.getElementById('btnGetExistingFiles').onclick = function(){
var ul = document.getElementById('listExisting');
//we split the files in a array
var existingFiles = "a.yml b.yml c.yml d.yml".split(" ");
//if the list already contains some values we remove them
if(ul.hasChildNodes()){
ul.empty();
}
//for each file we add an element in the list
existingFiles.forEach(function(fileName) {
console.log("add files");
var li = document.createElement("li");
var a = document.createElement("a");
a.setAttribute("href", "#");
a.setAttribute("class", "oneExistingFile");
a.appendChild(document.createTextNode(fileName))
li.appendChild(a);
ul.appendChild(li);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
<button id="btnGetExistingFiles" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu" id="listExisting">
</ul>
</div>
并且我不知道为什么我的元素有孩子尽管它在开头是空的但是无论如何即使我在浏览器终端中ul.empty()
当列表已满我也有错误
答案 0 :(得分:4)
虽然.empty()是一个jquery函数..我认为你需要使用ul.innerHTML = '';
而不是ul.empty()
document.getElementById('btnGetExistingFiles').onclick = function(){
var ul = document.getElementById('listExisting');
//we split the files in a array
var existingFiles = "a.yml b.yml c.yml d.yml".split(" ");
//if the list already contains some values we remove them
if(ul.hasChildNodes()){
ul.innerHTML = '';
}
//for each file we add an element in the list
existingFiles.forEach(function(fileName) {
console.log("add files");
var li = document.createElement("li");
var a = document.createElement("a");
a.setAttribute("href", "#");
a.setAttribute("class", "oneExistingFile");
a.appendChild(document.createTextNode(fileName))
li.appendChild(a);
ul.appendChild(li);
});
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
<button id="btnGetExistingFiles" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu" id="listExisting">
</ul>
</div>
&#13;
答案 1 :(得分:1)
没有Element.prototype.empty属性。 但是在jquery中有一个:
$(ul).empty();