jQuery .append() function

前端 未结 3 1929
礼貌的吻别
礼貌的吻别 2021-01-22 09:21

Why this

$(\"#mydiv\").append(\"
    \"); $(\"#mydiv\").append(\"
  • Hello
  • \"); $(\"#mydiv\").append(\"
\"); alert($(\"#mydiv\").
相关标签:
3条回答
  • 2021-01-22 09:40

    Append() appends DOM nodes, not HTML tags (i.e., it's an object append, not a string append).

    When you append <ul>, you are creating an entire UL node, with both start and end tags. The </ul> call is ignored.

    0 讨论(0)
  • 2021-01-22 09:51

    Because the browser needs to (re)build its DOM after each append. It can't know that a closing tag will come later, and an opening tag by itself is invalid, so error correction kicks in which in this case closes the unclosed element.

    This is one of the reasons why innerHtml and things that rely on it (such as jQuery's append method) are not reliable and should be avoided when possible.

    0 讨论(0)
  • 2021-01-22 10:05

    Because you can't append the unfinished pieces of HTML, you always append the element. For your case you have do either

    $("#mydiv").append("<ul></ul>");
    $("#mydiv ul").append("<li>Hello</li>");
    

    or

    $("#mydiv").append("<ul><li>Hello</li></ul>");
    
    0 讨论(0)
提交回复
热议问题