javascript 获取 HTML 注释标签内的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16753384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:51:26  来源:igfitidea点击:

Get text inside HTML comment tag?

javascriptjquery

提问by hao_maike

I have the following HTML:

我有以下 HTML:

<!--
<option value="HVAC">HVAC</option>
<option value="Cooling">|---Cooling</option>
<option value="Heating">|---Heating</option>
-->
....

I fetch this file dynamically using jQuery's get method and store it in a string variable named load_types.

我使用 jQuery 的 get 方法动态获取此文件并将其存储在名为load_types.

How can I strip the HTML comment tags and everything outside of them? I only want the inside HTML:

如何去除 HTML 注释标签以及它们之外的所有内容?我只想要内部 HTML:

<option value="HVAC">HVAC</option>
<option value="Cooling">|---Cooling</option>
<option value="Heating">|---Heating</option>

I tried to use the solutions herebut nothing worked properly--I just get nullas a match.

我尝试使用这里的解决方案,但没有任何效果 - 我只是null匹配。

Thanks for the help!

谢谢您的帮助!

回答by VisioN

Please never use regex to parse HTML. You can use the following instead:

永远不要使用正则表达式来解析 HTML。您可以改用以下内容:

var div = $("<div>").html(load_types),
    comment = div.contents().filter(function() {
        return this.nodeType === 8;
    }).get(0);

console.log(comment.nodeValue);

DEMO:http://jsfiddle.net/HHtW7/

演示:http : //jsfiddle.net/HHtW7/