doushi6932 2015-01-21 07:22
浏览 51

如何使用js创建html元素

I have html code which generates ads,And I am trying to generates these with help of js,I am generating last ad only.How can we get the all the ads in the division

Html code is:

<div class="list-group col-md-3" id="adsid">

        </div>

And JS code is:

for (var i = 0; i < s.length; i++) {
    var adid = s[i]['id']["0"];

    var desc1 = s[i]['desc']["0"];
    var desc2 = s[i]['desc2']["0"];
    var url = s[i]['url']["0"];
    $('#heading').html(s[i]['hea']["0"]);
    $('#desc1').html(s[i]['desc']["0"]);
    $('#desc2').html(s[i]['desc2']["0"]);
    $('#desturl').html(s[i]['url']["0"]);

    function create(htmlStr) {
        var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
        temp.innerHTML = htmlStr;
        while (temp.firstChild) {
            frag.appendChild(temp.firstChild);
        }
        return frag;
    }
    var fragment = create('<h4 class="list-group-item-heading"id="heading" name="heading"><font color="blue"></font></h4><p class="list-group-item-text"id="desc1" name="desc1"></p><p class="list-group-item-text"id="desc2" name="desc2"></p><p class="list-group-item-text" id="desturl" name="desturl"><font color="green"></font></p>');
    document.getElementById("adsid").appendChild(fragment);

}

And the ads are dynamic,it may vary based on the selection so it should be dynamic in nature.

As I am trying the above code I am getting only the last ad but not all .please help me out in this problem. And the sample output should be like this:

enter image description here

  • 写回答

1条回答 默认 最新

  • doujiena0025 2015-01-21 07:47
    关注

    remove all the js code above and replace it with this

    $( ".list-group" ).each(function( i ) { 
    var adid=s[i]['id']["0"],
        desc1=s[i]['desc']["0"],
        desc2=s[i]['desc2']["0"],
        url=s[i]['url']["0"],
        heading = $('<div id="heading">').html(s[i]['hea']["0"]),
        desc1 = $('<div id="desc1">').html(s[i]['desc']["0"]),
        desc2 = $('<div id="desc2">').html(s[i]['desc2']["0"]),
        desturl = $('<div id="desturl">').html(s[i]['url']["0"]);   
        $(this).append(heading)
           .append(desc1)
           .append(desc2)
           .append(desturl);
    });
    
    评论

报告相同问题?