jquery添加新的div onclick

时间:2013-05-01 16:01:50

标签: javascript jquery append

我有一个div列表

<li class="comment">
     <div class="comment-body" id="comment-body">
            <div class="comment-author vcard">
                <div class="lightbox-photo">
                    <a class="image-overlay" href='<%# "Foto/profil/foto_buyuk/" + Eval("Yorum_Profil_Foto_Buyuk") %>' data-rel="prettyPhoto" title='<%# Eval("Yorum_UserName")%>'><img src='<%# "Foto/profil/foto_kucuk/" + Eval("Yorum_Profil_Foto_Kucuk") %>' alt='<%# Eval("Yorum_UserName")%>' class="avatar" />
                    </a>
                 </div>
                 <cite class="fn"><asp:HyperLink ID="linkProfil" runat="server" Text='<%# Eval("Yorum_UserName")%>' NavigateUrl='<%# "~/profil.aspx?user_id="+Eval("User_ID") %>'></asp:HyperLink></cite>
                 <cite class="fn-time"></cite> 
               </div>
        <p><%# Eval("Yorum_Text")%></p>
           </div>
         </div>
     </div>
</li>

我想在div点击上添加一个新的div。我写了jquery代码,但它不起作用。

function addcommentdiv () {
    var NewContent = '<div class=""><input name="name" type="text" id="name" size="20" value="" style="height:20px; margin-top:10px; width:480px;margin-left:90px; font-size:14px;" /></div>'
    $('.comment-body').click(function () {

        var index2 = $('.comment-body').index(this);
        if (NewContent != '') {
            $('.comment-body').eq(index2).after(NewContent);
            NewContent = '';

        }
        else {
            $('.comment-body').eq(index2).next().toggle();

        }

    });

};

为什么它不起作用或如何在下面的点击div中添加一个新的div(作为twitter回复)?在我写一些代码之前。它工作但有一个问题:它只适用于一个div。

2 个答案:

答案 0 :(得分:3)

尝试

function addcommentdiv () {
    var NewContent = '<div class="reply"><input name="name" type="text" id="name" size="20" value="" style="height:20px; margin-top:10px; width:480px;margin-left:90px; font-size:14px;" /></div>'
    $('.comment-body').click(function () {
        var $this = $(this), $reply = $this.next('.reply');

        if ($reply.length) {
            $reply.toggle();
        } else {
            $(NewContent).insertAfter($this);
        }
    });
};

演示:Fiddle

答案 1 :(得分:0)

我对jquery不太熟悉,但你可以通过javascript添加一个新的div

var NewContent = '<div class=""><input name="name" type="text" id="name" size="20"          value="" style="height:20px; margin-top:10px; width:480px;margin-left:90px; font-  size:14px;" /></div>'


$('.comment-body').click(function () {
var newdiv=document.creatElement(NewContent);
var toattach= document.getElementById('comment-body');
toattach.appendchild(newdiv) ;
}
else {
    $('.comment-body').eq(index2).next().toggle();

}

});

相关问题