【问题标题】:How do I get an HTML comment with javascript如何使用 javascript 获取 HTML 注释
【发布时间】:2012-11-02 01:42:12
【问题描述】:

如果我有这个

  <!-- some comment -->

如何获取此元素并使用 javascript 更改内容? 如果我里面有一个代码,我想删除 cmets 的标签,我该怎么做?

【问题讨论】:

标签: javascript html


【解决方案1】:

我需要为整个网页存储一个模板。但是

我将 HTML 注释放在一个隐藏的

中,以便更轻松地检索该特定 HTML 注释中的文本,而不必费心将其与其他 HTML cmets 区分开来。

这是一个演示,展示了如何使用 createTreeWalker 检索 HTML 注释中的内容。

alert(
  document.createTreeWalker(
    document.getElementById('commentDiv'), 
    NodeFilter.SHOW_COMMENT, 
    null, 
    false
  ).nextNode().nodeValue
);
<p>Getting the text in a HTML-comment.</p>
<p>I use createTreeWalker to make sure we don't simply capture an empty text node by mistake. You could make the code even simpler, but then you must make sure that the &lt;div>-tag is immediately followed by the "&lt;!--", like this "&lt;div>&lt;!--". But if that breaks because of for example autoformating in an editor, so that you get a line feed in between or so, then the simpler method will fail. That is why I prefere to use the createTreeWalker here.</p>
<!--
  This is NOT the comment we want to get text from
-->
<div id="commentDiv" style="display:none;">
  <!--
    This is THE text, and you can have anything in here
    <>
    <div>
    <script>alert('hello');</script>
    etc.
    except of course an end of HTML-comment.

    An advantage of this way to store a template compared to using
    the <template>-tag, is that the <template>-tag can for example
    not contain a <html>-tag, in case you need to have a template
    for an entire web page.

    Check also my explanation down in the body text for why I use 
    createTreeWalker instead of some simpler code.
  -->
</div>
<!--
  This is also NOT the comment we want to get text from
-->
<p>End of body.</p>

【讨论】:

    【解决方案2】:

    使用 NodeIterator (IE >= 9)

    最好的方法是使用专用的NodeIterator 实例迭代给定根元素中包含的所有 cmets。

    See it in action!

    function filterNone() {
        return NodeFilter.FILTER_ACCEPT;
    }
    
    function getAllComments(rootElem) {
        var comments = [];
        // Fourth argument, which is actually obsolete according to the DOM4 standard, is required in IE 11
        var iterator = document.createNodeIterator(rootElem, NodeFilter.SHOW_COMMENT, filterNone, false);
        var curNode;
        while (curNode = iterator.nextNode()) {
            comments.push(curNode.nodeValue);
        }
        return comments;
    }
    
    window.addEventListener("load", function() {
        console.log(getAllComments(document.body));
    });
    

    使用定制的 DOM 遍历(也支持 IE

    如果你必须支持旧的浏览器(例如IE node type是Node.COMMENT_NODE的元素。

    See it in action!

    // Thanks to Yoshi for the hint!
    // Polyfill for IE < 9
    if (!Node) {
        var Node = {};
    }
    if (!Node.COMMENT_NODE) {
        // numeric value according to the DOM spec
        Node.COMMENT_NODE = 8;
    }
    
    function getComments(elem) {
      var children = elem.childNodes;
      var comments = [];
    
      for (var i=0, len=children.length; i<len; i++) {
        if (children[i].nodeType == Node.COMMENT_NODE) {
          comments.push(children[i]);
        }
      }
      return comments;
    }
    

    提取节点内容并删除

    无论您从上面选择的方式如何,您都会收到相同的节点 DOM 对象。

    访问评论内容就像commentObject.nodeValue 一样简单。
    删除评论有点冗长:commentObject.parentNode.removeChild(commentObject)

    【讨论】:

    【解决方案3】:

    你必须遍历 DOM 才能得到它。 评论DOM元素的nodeType是8

    if( oNode.nodeType === 8 ) {
      oNode.parentNode.removeChild( oNode );
    }
    

    将是一种方法

    【讨论】:

      【解决方案4】:

      这是一个检索 cmets 的 JQuery 插件:

      http://www.bennadel.com/blog/1563-jQuery-Comments-Plug-in-To-Access-HTML-Comments-For-DOM-Templating.htm

      基本思路是看nodes,而不是elements:

      http://www.w3schools.com/htmldom/dom_nodes.asp

      您从document 对象开始,并使用childNodes 集合遍历它们。您必须检查node.nodeType == 8,它将仅返回注释节点(请注意,您需要递归地遍历子节点)。

      【讨论】:

      • 没有Jquery就没有办法吗?我想知道如何用纯 javascript 做到这一点
      • 没有什么事情是 jQuery 能做的,而纯 JavaScript 做不到的。 jQuery 不会向浏览器的 JavaScript 引擎添加任何内容;它只是一个实用程序库,用于抽象已有的内容。
      猜你喜欢
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      • 2018-10-13
      • 2010-09-28
      • 2014-01-11
      • 2011-04-14
      • 2011-08-31
      • 2017-02-24
      相关资源
      最近更新 更多