Jquery function closing div on append by itself

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

I have the following function:

function displayResults(Items) {
                $(\"#result\").text(\"\");
                $(\"#result\").append(\'
相关标签:
3条回答
  • 2021-01-11 11:54

    This is an issue I've just come across too. An option is to create the div containers first in a loop then populate them after as you require:

    for(var i = 0; i < 12; i++){
    
        $(el).append('<li class="scene-block"></li>'); // create container li tags
    
        //fill empty li tags with content
        for(var j = 0; j < 2; j++){
            $(el).find('li').last().append('<div class="select-a-scene-bg"></div>');
        }
    
    }
    
    0 讨论(0)
  • 2021-01-11 11:55

    You can use a array with join to solve this

    function displayResults(Items) {
        $("#result").text("");
        var array = [];
        array.push('<div class="car-offers">');
        array.push('<div class="purple"></div>');
        array
                .push('<img src="images/caroffer.jpg" alt="" title="" width="213" height="117" />');
        array.push('<h3>titleeee</h3>'); // ' + Items[i].Title + '
        array.push('<span>Year: 2003</span>');
        array.push('<span>Milage: 172,000 Km</span>');
        array.push('<span class="price">53,000 QR</span>');
        array.push('<a href="">Link</a>');
        array.push('</div>');
    
        array.push('<div class="car-offers">');
        array.push('<div class="purple"></div>');
        array
                .push('<img src="images/caroffer.jpg" alt="" title="" width="213" height="117" />');
        array.push('<h3>titlee22</h3>'); // ' + Items[i].Title + '
        array.push('<span>Year: 2003</span>');
        array.push('<span>Milage: 172,000 Km</span>');
        array.push('<span class="price">53,000 QR</span>');
        array.push('<a href="">Link</a>');
        array.push('</div>');
        $("#result").text(array.join(''));
    }
    
    0 讨论(0)
  • 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('<div class="car-offers">');
    

    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.

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