如何在Javascript或jQuery的评论中包装标签

时间:2015-09-29 08:16:42

标签: javascript jquery html

我想收看我的评论 我想在运行时禁用一些标签和脚本,

<div id="some-div">
    <img src="http://placekitten.com/200/300"/>
    <img src="http://placekitten.com/200/150"/>
    <img src="http://placekitten.com/350/330"/>
</div>

$(function ()
{
    $('img').wrap('<!---></--->');
});

但他们不会包裹他们删除我的标签 见演示 http://jsfiddle.net/p8nbpt7o/1/

2 个答案:

答案 0 :(得分:1)

您可以使用 document.createComment() 创建评论节点,并使用 replaceChild() img替换为评论节点

&#13;
&#13;
$('img').each(function() {
  parent = this.parentNode;
  parent.replaceChild(document.createComment(this.outerHTML), this);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="some-div">
  <img src="http://placekitten.com/200/300" />
  <img src="http://placekitten.com/200/150" />
  <img src="http://placekitten.com/350/330" />
</div>
&#13;
&#13;
&#13;

或者您可以在jQuery中使用 replaceWith()

&#13;
&#13;
$('img').each(function() {
  $(this).replaceWith(document.createComment(this.outerHTML));
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="some-div">
  <img src="http://placekitten.com/200/300" />
  <img src="http://placekitten.com/200/150" />
  <img src="http://placekitten.com/350/330" />
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

直接在HTML中

HTML评论以<!--开头,以-->结尾。

如果您想在HTML中对所有标记进行评论,可以这样做:

<!--
<img src="http://placekitten.com/200/300"/>
<img src="http://placekitten.com/200/150"/>
<img src="http://placekitten.com/350/330"/>
-->

如果您想在HTML中单独评论所有代码,可以这样做:

<!--<img src="http://placekitten.com/200/300">-->
<!--<img src="http://placekitten.com/200/150">-->
<!--<img src="http://placekitten.com/350/330">-->

使用jQuery

如果您想使用jQuery,可以使用replaceWith代替wrap

$(function(){
    $('img').replaceWith(function() {
        return "<!--" + this.outerHTML + "-->";
    });
});

结果:

<!--<img src="http://placekitten.com/200/300">-->
<!--<img src="http://placekitten.com/200/150">-->
<!--<img src="http://placekitten.com/350/330">-->

我在Chrome,Firefox和IE11中尝试过,它对我来说很好用!

小提琴:

<强> http://jsfiddle.net/p8nbpt7o/3/