【发布时间】:2017-06-03 05:23:41
【问题描述】:
我在 head 标签中有两个注释标签。我只想取消评论第二条评论。
var x = "<html><head><!-- <#if> I don't want any change </#if> --><!-- <#if>I want to uncomment </#if> --></head></html>";
$(x).contents().each(function(index, node) {
if (node.nodeType == 8) {
$(node[0]).replaceWith(node.nodeValue);
}
});
alert(x);
输出应该是:
<html>
<head>
<!-- <#if> I don't want any change </#if> -->
<#if> I want to uncomment </#if>
<head>
</html>
【问题讨论】:
-
您实际上想要完成什么?对我来说,在页面加载后尝试编辑页面标题很可能不是您正在做的任何事情的最佳方法。
-
这听起来像 xy 问题,你在评论中有什么?
-
this的可能重复
-
对
$(x)中的 DOM 进行更改不会修改原始字符串。您需要执行dom = $(x)之类的操作,然后使用dom.contents(),最后使用alert(dom.html()) -
var parts = x.split("<!-- "); parts[2]=parts[2].replace(" -->",""); parts[1] = "<!-- " + parts[1]; console.log(parts.join(""));
标签: javascript jquery