简体   繁体   English

如何用jQuery中动态生成的元素替换Div元素?

[英]How to replace Div elements with dynamically generated elements in jQuery?

I have a div structure like this 我有这样的div结构

<div class="col-md-12" id="dvInsert">
    // insert dynamic generated elements 
</div>

I am decoding HTML elements and want to append to existing div but its showing div structure in browser like this: 我正在解码HTML元素,并希望追加到现有的div,但它在浏览器中显示的div结构如下:

     <div class="col-md-12">
         <p>Hello this is my new paragraph</p>
     </div>


function htmlDecode(value) {

         $("#dvInsert").append($('<div/>').html(value).text());
     }

I have also tried this but its also shwoing div strcuture rather then text. 我也尝试过,但是它也显示了div结构而不是文本。

 $($('<div/>').html(value).text()).appendTo("#dvInsert");

Value of value is &amp;lt;div class="row"&amp;gt;&lt;div&gt;&amp;nbsp; &amp;nbsp;&amp;lt;div class="col-md-12"&amp;gt;&lt;/div&gt;&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;lt;p&amp;gt;Hello this is my new paragraph&amp;lt;/p&amp;gt;&lt;/div&gt;&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;lt;/div&amp;gt;&lt;/div&gt;&lt;div&gt;&amp;lt;/div&amp;gt;&lt;/div&gt; 值的值为&amp;lt;div class="row"&amp;gt;&lt;div&gt;&amp;nbsp; &amp;nbsp;&amp;lt;div class="col-md-12"&amp;gt;&lt;/div&gt;&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;lt;p&amp;gt;Hello this is my new paragraph&amp;lt;/p&amp;gt;&lt;/div&gt;&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;lt;/div&amp;gt;&lt;/div&gt;&lt;div&gt;&amp;lt;/div&amp;gt;&lt;/div&gt; &amp;lt;div class="row"&amp;gt;&lt;div&gt;&amp;nbsp; &amp;nbsp;&amp;lt;div class="col-md-12"&amp;gt;&lt;/div&gt;&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;lt;p&amp;gt;Hello this is my new paragraph&amp;lt;/p&amp;gt;&lt;/div&gt;&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;lt;/div&amp;gt;&lt;/div&gt;&lt;div&gt;&amp;lt;/div&amp;gt;&lt;/div&gt;

What goes inside .append as parameter should be an jquery object. .append作为参数的内容应该是一个jquery对象。 In your case, you are already creating an object with this: $('<div/>').html(value) . 在您的情况下,您已经在使用以下对象创建一个对象: $('<div/>').html(value) You just need to discard .text() . 您只需要丢弃.text() In short, you need to change this 简而言之,您需要对此进行更改

$('<div/>').html(value).text() 

to

$('<div/>').html(value)

My Friend Hope you have to just replace the existing div you can try something like this below 我的朋友希望您只需替换现有的div,即可在下面尝试类似的操作

$("#div1").replaceWith("<div>I'm new!</div>");

For more details about replace with Read 有关使用Read替换的更多详细信息

you can try to run it twice: 您可以尝试运行两次:

var escaped1 = $('<div/>').html(value).text();
var escaped2 = $('<div/>').html(escaped1).text();

$("#dvInsert").append($(escaped2));

but I'm sure that there is a better way... 但我相信还有更好的方法...

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

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