【问题标题】:How to remove html comment using jQuery?如何使用 jQuery 删除 html 注释?
【发布时间】:2014-04-21 19:04:16
【问题描述】:

我正在尝试使用 jQuery 删除 html cmets(<!-- -->),然后使用幻灯片或显示在 div 中显示一些 <article> 元素。我这样做而不是直接使用 .hide 的原因是因为当我使用 .hide 时,隐藏的 <article> 的高度仍然显示,因此容器 div 下面有空白空间。

这可能吗?

【问题讨论】:

  • 嗯,不!当某些东西被隐藏时,它不会占用空间。您可能一直在使用可见性,这确实会占用空间。使用 display 属性来做,使用 cmets 是完全错误的,而且要难一百倍。
  • 我不认为 cmets 进入 DOM,所以你不能像你最初指定的那样去做。
  • @Barmar - 它们是 DOM 的一部分,甚至有一个 nodeType 以便可以过滤它们,但您通常不需要在 javascript 中使用它们。

标签: jquery html comments hide


【解决方案1】:

使用jquery uncomment plugin可以删除

这是库文件

library

Romuald Brunet 的库代码

   (function($) {
    $.fn.uncomment = function(recurse) {
        $(this).contents().each(function() {
            if ( recurse && this.hasChildNodes() ) {
                $(this).uncomment(recurse);
            } else if ( this.nodeType == 8 ) {
                // Need to "evaluate" the HTML content,
                // otherwise simple text won't replace
                var e = $('<span>' + this.nodeValue + '</span>');
                $(this).replaceWith(e.contents());
            }
        });
    };
})(jQuery);

例子---

 <p id="uncomment">
  The <!-- <em>quick</em> brown -->
  fox jumps over the <!-- lazy --> dog <br />
  <a href="#">Click here to reveal <!-- hidden --> comments</a>
</p>
<script type="text/javascript">
$('#uncomment a:last').click(function(e) {
    e.preventDefault();

    $('#uncomment').uncomment(/* recurse */ true );
});
</script>

【讨论】:

    猜你喜欢
    • 2018-07-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 2015-03-28
    • 2016-09-05
    • 2012-07-05
    相关资源
    最近更新 更多