替换正文,但不替换其中的脚本


<body>
   <div>blabla</div>
   <div>blabla2</div>
   <script>
      ....
   </script>
</body>

我想替换正文的所有内容,但保留脚本标签和脚本标签中的内容不变。

如果我这样做$('body').html('<span>hello</span>')它将替换整个内容,因此它看起来像:

<body>
  <span>hello</span>
</body>

但我想要的是让它看起来像:

<body>
  <span>hello</span>
  <script>...</script>
</body>

基本上替换正文中的所有内容,除了脚本。 这可能吗?

如果你知道你的脚本是 body 元素中的最后一个脚本(通常是这种情况),你可以这样做:

$("body *:not(script:last)").remove();
$("body").prepend($("<div>Test!</div>"));

小提琴:https://jsfiddle.net/cq43bvam/1/

$("body").contents().not("script").remove();
$("<div>Test!</div>").prependTo("body");

文档: contents()prependTo() .

这假定脚本是正文的子级。如果它们可以嵌套得更深,请先执行以下命令:

$("body * script").appendTo("body");

如果你替换正文中的整个html,显然它会从中删除所有内容。

最好的方法是在单独的变量中定义脚本,然后替换主体,然后将该变量附加到主体中

var scriptHtml = $('body').find('script');
$('body').html('<span>hello</span>');
$('body').append(scriptHtml);

尝试使用以下代码:

$('body').html('<span>hello</span><script>'+$('body script').html()+'</script>');

只需找到div 并删除....

$('body').prepend('<span>hello</span>').find("div").remove();

您可以将 remove() 方法与:not()选择器一起使用,例如

$(document.body).find(':not(script)').remove();
// body is clear. do whatever you want.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  var test1;
</script>
<span>hello</span>
<script>
  var test2;
</script>
<p>how<span>are</span>
</p><span>you</span>

最新更新