简体   繁体   English

如何在html中注入div?

[英]how to inject div in an html?

I have a html string as follow: 我有一个html字符串,如下所示:

<div data-field-id="ListFieldId1" data-field-type="ListField">
            <div id="1">
                <div>
                    some text
            </div>
            <img src="source" />
            <div>
                some text
            </div>
            <div>
                some text
            </div>
            <a href="link">click</a>
        </div>
    </div>

in my web page I have a button that when pressed the div part by id="1" should be injected to the main div with id="2" using jquery. 在我的网页中,我有一个按钮,当按下id="1"div部分时,应该使用jquery将其注入id="2"的主div I tried in this way that i have variable listHtml equals <div id="1">...</div> and listCount as default id. 我以这种方式尝试过,使变量listHtml等于<div id="1">...</div>并将listCount作为默认ID。 I tried to set a new id for listHtml in this way: 我试图通过这种方式为listHtml设置新的ID:

listHtml.attr('id', (listCount + 1).toString());

but this line doesn't work! 但是这行不起作用!

in fact after this work I want to append(listHtml) . 实际上,在完成这项工作之后,我想append(listHtml)

how can I fix it? 我该如何解决?

Is there any other way to inject a div tag to html? 还有其他方法可以将div标签注入html吗?

thanks. 谢谢。

那应该完成$.('#1').append($('<div id="'+(listid+1)+'">...</div>'));

You have to create Jquery Object before you want to make change in any attribute of that element. 要更改该元素的任何属性,必须先创建Jquery Object。 Otherwise it treated it as simple string not an element. 否则,它将其视为简单字符串而不是元素。

For Example 例如

var listHtml = '<div id="1">New Div</div> ';
var ele = $(listHtml);
ele.attr('id', (listCount + 1).toString()); //here you can make change in id attribute.    

May this will help you. 愿这对您有帮助。

Here is JsFiddle Demo to add dynamic div. 这是添加动态div的JsFiddle演示

I hope the following code lines may help you, if I understand your problem correctly. 如果我正确理解您的问题,希望以下代码行可以为您提供帮助。

Note: I have included "id" on divs etc for brevity and for quick readability. 注意:为简短起见和快速阅读,我在div等上添加了“ id”。

<input id="btnAdd" type="button" value="Add Div" />
<div id="divMain" data-field-id="ListFieldId1" data-field-type="ListField">
    <div id="1">
        <div>
            some text
        </div>
        <img src="source" />
        <div>
            some text
        </div>
        <div>
            some text
        </div>
        <a href="link">click</a>
    </div>
</div>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script>
    $("#btnAdd").click(function () {
        var div = $("#divMain").children('div').last();
        var nextDivId = div.attr("id");

        var newDiv = div.clone();
        newDiv.attr("id", Number(nextDivId) + 1);
        $("#divMain").append(newDiv);
    });
</script>
function addNewDiv()
{
    $("#yourDiv").append('<div id="'+ listCount++ +'">Div "' + listCount  +'" </div>');   
}

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM