Empty 不是函数

Jer*_*ome 4 javascript jquery drop-down-menu

我在查找代码中的错误以删除列表中的所有子项时遇到了一些麻烦:

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);
    });
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

我不知道为什么我的元素有孩子,尽管它一开始是空的,但无论如何,即使我ul.empty()在列表已满时在浏览器终端中这样做,我也有错误

Moh*_*sef 7

虽然.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);
    });
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)