使用JS或Jquery读取HTML注释

时间:2014-03-21 14:53:11

标签: javascript jquery html comments

是否可以阅读用HTML编写的评论? 我猜评论不构成DOM的一部分,因此选择它们或晚上分配课程或id可能不是一种选择。

有没有什么方法可以阅读正文的内容并获得一系列评论或类似内容? Jquery还可以。

我想创建一个插件或函数来执行以下操作:

<!-- top -->
<div>top stuff</div>

<!-- Content -->
<div>content stuff</div>

<script>

   var comments = $('body').getComments();
   alert(comments[0]); //returns "top"
   alert(comments[1]); //return "Content"
</script>

感谢。

2 个答案:

答案 0 :(得分:12)

您可以使用以下代码段:

DEMO jsFiddle

$.fn.getComments = function () {
    return this.contents().map(function () {
        if (this.nodeType === 8) return this.nodeValue;
    }).get();
}

答案 1 :(得分:2)

这是我的Firebug控制台的输出:

>>> document.body.innerHTML = '<!-- comment -->';
"<!-- comment -->"

>>> document.body.childNodes
NodeList[Comment { data=" comment ", length=9, nodeType=8, more...}]

>>> document.body.childNodes[0]
Comment { data=" comment ", length=9, nodeType=8, more...}

>>> document.body.childNodes[0].data
" comment "

简而言之,JavaScript的DOM将像其他标记一样获取注释。它们的类型为Comment。您可以查找他们的data属性以获取评论内容。

[编辑]

我没有在Firefox 26以外的任何浏览器中检查过这个;你可能想调查一下。

相关问题