在JQuery中构建div结构并追加到另一个Div

时间:2017-02-16 06:12:01

标签: javascript php jquery html json

HTML

<div class="post-preview">
    <a href="javascript:void(0)" class="delete btn-delete" "><i class="glyphicon glyphicon-remove "></i></a>
            <a href="javascript:void(0) " class="delete btn-edit " "><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a>

    <a href="javascript:void(0)">
        <h4 class="post-title">
            some value
        </h4>
        <h4 class="post-subtitle">
            some value
        </h4>
    </a>

    <p class="post-meta">Posted by <a href="#"> some value </a> on date</p>
</div>

Jquery的

var item = dataobj[i];
alert(item.pid + item.ptitle + item.pdes + item.email + item.fname + item.postedby + item.DE);
var $maindiv = $("<div/>").addClass("post-preview");
var $a1 = $("<a/>").addClass("delete btn-delete").attr("href", "javascript:void(0)").attr("rel", item.pid);
var $removeicon = $("<i/>").addClass("glyphicon glyphicon-remove");
var $a2 = $("<a/>").addClass("delete btn-delete").attr("href", "javascript:void(0)").attr("rel", item.pid);
var $editicon = $("<i/>").addClass("fa fa-pencil-square-o").attr("aria-hidden", true);
var $a3 = $("<a/>").addClass("PostBody");
var $h1 = $("<h4/>").addClass("post-title").html(item.ptitle);
var $h2 = $("<h4/>").addClass("post-subtitle").html(item.pdes);
var $p = $("<p/>").html("Posted by");
var $a4 = $("<a/>").attr("href", "javascript:void(0)").html(item.fname + " - " + item.email);
var $myobj =
    (item.DE == 1 ? $maindiv
        .append($a1.append($removeicon))
        .append($a2.append($editicon)) : '');
$maindiv
    .append($a3.append($h1)
        .append($h2)
    )
    .append($p.append($a4));
//now append it to your html
$myobj.appendTo('body');

1 个答案:

答案 0 :(得分:1)

您可以使用Jquery方法.prependTo()将匹配元素集中的每个元素插入到目标的开头。