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

4
我有一个HTML字符串,我想在任意位置将另一个HTML字符串追加到其中。
例子:
var htmlString = '<div id="insert"> <p> Hello </p> </div>'

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

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

显然,这种方法行不通,因为它无法直接插入字符串。但是,我不想将htmlString转换为jQuery对象,因为这会破坏HTML文档的结构,而且我需要脚本标签保持在它们被插入的位置。

希望这足够清楚了。

编辑:

抱歉,我认为我解释得不够清楚。

我有一个包含表格的HTML字符串,我想向表格中添加新行。我的问题是,我有许多<script>标签,我需要它们保留在原来的位置。当我将字符串转换为$(string)时,我就无法将其返回到原始形式:

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

这是我正在使用的Confluence页面,我只能修改现有内容,源代码访问权限受限。
HTML字符串来自于Confluence上另一个页面的AJAX请求,我需要确保脚本代码不变,以便其他宏功能正常运行。
我已经在JS Bin中提供了一个示例,希望清楚地说明我的问题。 https://jsbin.com/ruwawuzica/edit?html,js,output
2个回答

4

您可以这样做:

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>

因为$(htmlString)是用jquery包装的<div id="insert"></div>元素。


问题所问是如何在HTML的id="insert"部分插入“good by a string”,而您所建议的是如何追加HTML。 - Mehul Kothari

2

你好 @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!!!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接