如何使用jquery添加html标记

时间:2013-01-15 10:37:05

标签: jquery ajax

我用这个写了以下函数我在Html中显示ajax响应

function loadData() {
        $.ajax({
            type: "post",
            url: "http://127.0.0.1/get_scroll_rec/",
            cache: false,               
            data:'',
            success: function(response){
                var obj = JSON.parse(response);
                try{
                    var str = '';
                    var items=[];   
                    $.each(obj[0], function(i,val){ 

                                                    //Here display code

                            items.push($('<div id="recent">').html(val.Title));
                            items.push($('<h1>').html(val.name));
                            items.push($('<p>').html(val.desciption));
                            items.push($('<div id="recent_created" class="recent_created">').html(val.added_on));
                    }); 

                    $('#recent_rightwrapper1').fadeOut('slow', function() {
                        $(this).append(str).fadeIn('slow').fadeIn(3000);
                        $('#recent_rightwrapper1').css({backgroundColor: ''});
                        $('#recent_rightwrapper1').append.apply($('#recent_rightwrapper1'), items);
                    }).css({backgroundColor: ''});

                }catch(e) {     
                    alert('Exception while request..');
                }       
            },
            error: function(){                      
                alert('Error while request..');
            }
         });


    }

});

我可以在这个显示区域代码中添加一些HTMl标签 喜欢(改为第1行&#34; h1&#34;添加标签,更改为第2行&#34;添加&#34;标签) 想在最后一行5号添加没有数据的div。

1> items.push($('<div id="recent"><h1>').html(val.Title));
2> items.push($('<h1><a href="" target="_blank">').html(val.name));
3> items.push($('<p>').html(val.desciption));
4> items.push($('<div id="recent_created" class="recent_created">').html(val.added_on));
5> items.push($('<div id="blank">')

1 个答案:

答案 0 :(得分:0)

通过append子节点附加到现有元素。

$("#yourRoot").append($('<div id="blank">'));

编辑: append适用于任何jQuery对象,也适用于您刚刚通过提供HTML文本创建的对象。因此,如果您想将空div附加到第一行中的元素,则只需执行以下操作:

var $firstLine = $('<div id="recent"><h1>').html(val.Title);
var $lastLine = $('<div id="blank">');
$firstLine.append($lastLine);
items.push($firstLine);