jQuery comment/uncomment& lt !!-element-& gt; [英] jQuery comment/uncomment <!--element-->

查看:64
本文介绍了jQuery comment/uncomment& lt !!-element-& gt;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用jQuery将元素包装到注释中的方法,例如:

I am looking for a way to wrap, with jQuery, an element into a comment, like:

<!--
<div class="my_element"></div>
-->

以及删除评论的方法.

这可能吗?

推荐答案

将带有注释的元素包装起来,或更具体地说,将元素替换为具有该元素的HTML的注释节点:

To wrap an element with comment, or more specifically to replace an element with a comment node having that element's HTML:

my_element_jq = $('.my_element');
comment = document.createComment(my_element_jq.get(0).outerHTML);
my_element_jq.replaceWith(comment);

要切换回去:

$(comment).replaceWith(comment.nodeValue);

如果您没有对注释节点的引用,则需要遍历DOM树并检查每个节点的 nodeType .如果其值为8,则为注释.

If you don't have the reference to the comment node then you need to traverse the DOM tree and check nodeType of each node. If its value is 8 then it is a comment.

例如:

<div id="foo">
    <div>bar</div>
    <!-- <div>hello world!</div> -->
    <div>bar</div>
</div>

JavaScript:

JavaScript:

// .contents() returns the children of each element in the set of matched elements,
// including text and comment nodes.
$("#foo").contents().each(function(index, node) {
    if (node.nodeType == 8) {
        // node is a comment
        $(node).replaceWith(node.nodeValue);
    }
});

这篇关于jQuery comment/uncomment&amp; lt !!-element-&amp; gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆