简体   繁体   English

在jQuery中将HTML附加到HTML字符串

[英]Append HTML to HTML string in jQuery

I have a HTML string and I want to append another html string to this in some arbitrary location. 我有一个HTML字符串,我想在一些任意位置附加另一个HTML字符串。

Example: 例:

var htmlString = '<div id="insert"> <p> Hello </p> </div>'

var appendString = '<p> Goodbye </p>'

$(appendString).appendTo( $(htmlString).find('#insert') )

Obviously that doesn't work because it cannot insert directly into the string however, I do not want to convert htmlString into a jQuery object because it messes up the structure of the HTML document and I need the script tags to remain in the locations they have been inserted. 显然这不起作用,因为它无法直接插入字符串,但是,我不想将htmlString转换为jQuery对象,因为它弄乱了HTML文档的结构,我需要脚本标记保留在他们拥有的位置插入。

Hope that's clear enough. 希望足够清楚。

EDIT: 编辑:

My apologies, I think I explained my problem poorly. 道歉,我想我的问题解释得很糟糕。

I have a HTML string that includes a table and I want to append a new row to the table. 我有一个包含表格的HTML字符串,我想在表格中附加一个新行。 My problem is that I have a number of <script> tags that I need to remain in their locations. 我的问题是我有一些<script>标签需要保留在他们的位置。 When I convert the string into a $(string), I am then unable to return it to its original form: 当我将字符串转换为$(字符串)时,我无法将其返回到其原始形式:

var htmlString = $('body').html();
var $htmlString = $(x);
console.log($htmlString.html());

This is a Confluence page that I attempting to do this on and I have limited access to the source; 这是一个Confluence页面,我试图这样做,我有限的访问源; most I can do is to modify what is already there. 我能做的最多就是修改已有的东西。

The HTML string comes from a AJAX request of another page on Confluence and I need the scripts to remain in the same place so that my other macros will run correctly. HTML字符串来自Confluence上另一个页面的AJAX请求,我需要脚本保留在同一个位置,以便我的其他宏可以正确运行。

I have included a JS Bin example of my problem to hopefully illustrate my problem clearly. 我已经包含了我的问题的JS Bin示例,希望能够清楚地说明我的问题。

https://jsbin.com/ruwawuzica/edit?html,js,output https://jsbin.com/ruwawuzica/edit?html,js,output

You can do it like this: 你可以这样做:

 var htmlString = '<div id="insert"> <p> Hello </p> </div>'; var appendString = '<p> Goodbye </p>'; var added = ($(htmlString).append($(appendString))); $(added).appendTo('div'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div> 

Since $(htmlString) is the element <div id="insert"></div> wrapped in jquery 由于$(htmlString)是包含在jqueryelement <div id="insert"></div>

Hi @MyLittleDax i guess you can do this: 嗨@MyLittleDax我想你可以这样做:

var htmlString = "<div id='insert'> <p> Hello </p> </div>";
var appendString = "<p> Goodbye </p>";
//your container where you put the html
var container = $('#container'); 
container.empty();
container.append(htmlString);
var insert = $('#insert');
insert.append(appendString);

good luck!!! 祝好运!!!

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

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