Jquery function closing div on append by itself

前端 未结 3 688
旧巷少年郎
旧巷少年郎 2021-01-11 11:12

I have the following function:

function displayResults(Items) {
                $(\"#result\").text(\"\");
                $(\"#result\").append(\'
3条回答
  •  梦谈多话
    2021-01-11 11:58

    You cannot append incomplete fragments of HTML with .append(). Unlike document.write, jQuery's .append() method parses the passed string into elements before appending them to the DOM.

    So when you do:

    $("#result").append('
    ');

    jQuery parses the given string into a div element and assigns the car-offers value to its className property, then appends the newly created element to the #result element.

    Appending the whole HTML string in a single operation will fix that, so jQuery knows how to parse the given string correctly.


    Personally, I wouldn't suggest putting that much HTML inside of a JS file. You can consider putting that inside of a div with display:none then simply call .show() on it. Or have it initially in the page, .detach() it storing in a variable and .append() it back when necessary.

提交回复
热议问题