如何使用 Jquery 替换或覆盖容器中追加的 html 字符串

How to replace or override the appended html string from a container using Jquery

本文关键字:追加 html 字符串 Jquery 何使用 替换 覆盖      更新时间:2023-09-26

有一个包含画布的容器:

<div id="container1">
<canvas id="canvas1" width="378" height="500" > </canvas>
</div>

从JS中,我将一个html字符串附加到此容器。

$("#Container1").append(html_string1);

并在 UI 上成功呈现。

现在从我的角度来看,html 字符串被修改了,它再次调用 js 方法将 html 字符串附加到容器中,但这次它删除了画布并且它不会出现在 UI 上。

我尝试过使用以下方法:

$("#Container1").html(html_string1);
$("#Container1").replaceWith(html_string1);

但他们都失败了。这里有任何帮助吗?

你需要使用 append,就像你第一次做的那样:

$("#Container1").append(html_string1);

如果您替换container1的 html,那么您也将替换画布,当您这样做时会发生这种情况:

$("#Container1").html(html_string1);

$("#Container1").replaceWith(html_string1);

如果你想删除添加的html,你必须执行以下操作:

$("#html_string_added").remove();
听起来您希望

能够将html_string放在 Container1 中并多次这样做,每次都覆盖上一个字符串。在这种情况下,我会在您的画布之前或之后添加一个元素并添加到其中。

<div id="container1">
<p id="text"></p>
<canvas id="canvas1" width="378" height="500" > </canvas>
</div>
$('#text').html(html_string);

然后,可以轻松地设置html_string内容的样式,而不会影响画布。