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
Get text inside HTML comment tag?
提问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 null
as 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);