【问题标题】:Jquery uncomment the second child inside head tagJquery取消注释head标签内的第二个孩子
【发布时间】: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("&lt;!-- "); parts[2]=parts[2].replace(" --&gt;",""); parts[1] = "&lt;!-- " + parts[1]; console.log(parts.join(""));

标签: javascript jquery


【解决方案1】:

也许

var x = document.getElementsByTagName("head")[0].innerHTML;

var parts = x.split("<!-- "); 
parts[2]=parts[2].replace(" -->",""); 
parts[1] = "<!-- " + parts[1]; 
document.getElementsByTagName("head")[0].innerHTML=parts.join("");

【讨论】:

  • 'x' 包含 html 字符串。是否可以从变量 x 中定位 head 标签并做这些事情?
  • 用你的字符串代替我的第一句话
猜你喜欢
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
  • 2017-03-11
  • 2011-04-07
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多