jQuery Append String vs Object Containing String

后端 未结 2 768
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-22 15:01

I understand that both of these will insert html into an element.

What are the differences between these 2 methods though?

String:

$(\"div\").app         


        
相关标签:
2条回答
  • 2021-01-22 15:35

    Is it just that you can do stuff like this?

    $("div").append($("<h1></h1>").html("Header"));
    

    Exactly

    Doing it this way creates for you a jQuery object which can further be manipulated with functions like append, css, addClass

    $("div").append($("<h1></h1>").html("Header")
                                  .addClass("someClass")
                                  .css("color", "gree"));
    

    Or if you don't want to do further manipulation like this, then by all means pass it just a string, and you'll get the same result.

    0 讨论(0)
  • 2021-01-22 15:35

    In your example there's no practical difference. The function accepts strings because you might want to add a new element which doesn't have a jQuery object yet, and it accepts jQuery objects because you might want to append an existing element or a complex object that doesn't have a string representation.

    0 讨论(0)
提交回复
热议问题