appenChild不是我的php页面中的函数

时间:2018-09-04 12:14:57

标签: javascript dom

大家好,为什么它返回“ appenChild不是函数?”

function showBooks(ajax) {
         var books = ajax.responseXML.getElementsByTagName("book");
for (var i = 0; i < books.length; i++) {
    var titleNode  = books[i].getElementsByTagName("title")[0];
    var authorNode = books[i].getElementsByTagName("author")[0];
    var title  = titleNode.firstChild.nodeValue;
    var author = authorNode.firstChild.nodeValue;
    var year = books[i].getAttribute("year");

    var li = document.createElement("li");
    li.innerHTML = title + ", by " + author + " (" + year + ")";
    $("books").appendChild(li);
}

在我不包含这些内容的页面中,它可以正常工作。如果我包含theese js,它将无法正常工作。我需要所有这些javascript

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> 
   </script> 
    <script src="js/bootstrap.min.js" ></script>
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <!-- Plugin JavaScript -->
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>

对不起,我在javascript上不能做很多事

1 个答案:

答案 0 :(得分:1)

$("books")是一个jQuery对象,而不是HTMLElement,因此它没有像appendChild这样的HTMLElement方法。 jQuery Objects是$(...).append(),适用于您的情况:

function showBooks(ajax) {
  var books = ajax.responseXML.getElementsByTagName("book");
  for (var i = 0; i < books.length; i++) {
    var titleNode = books[i].getElementsByTagName("title")[0];
    var authorNode = books[i].getElementsByTagName("author")[0];
    var title = titleNode.firstChild.nodeValue;
    var author = authorNode.firstChild.nodeValue;
    var year = books[i].getAttribute("year");

    var li = document.createElement("li");
    li.innerHTML = title + ", by " + author + " (" + year + ")";
    $("#books").append(li); // use jQuery append method instead of appendChild
  }
}

或者您可以获取基础HTMLElement并在其上使用appendChild

function showBooks(ajax) {
  var books = ajax.responseXML.getElementsByTagName("book");
  for (var i = 0; i < books.length; i++) {
    var titleNode = books[i].getElementsByTagName("title")[0];
    var authorNode = books[i].getElementsByTagName("author")[0];
    var title = titleNode.firstChild.nodeValue;
    var author = authorNode.firstChild.nodeValue;
    var year = books[i].getAttribute("year");

    var li = document.createElement("li");
    li.innerHTML = title + ", by " + author + " (" + year + ")";
    $("#books").get(0).appendChild(li)); // use appendChild on the HTMLElement
  }
}