jQuery comment / uncomment<! - element - > [英] jQuery comment/uncomment <!--element-->

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

问题描述

我正在寻找一种方式,用jQuery包装一个元素到一个注释中,例如:

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

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

,也是删除评论的方式。

and also a way to remove the comments.

这可能吗?因为我找不到任何相关的。

Is this possible? because I couldn't find nothing related.

推荐答案

使用注释包装一个元素,注释节点具有该元素的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&lt;! - element - &gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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