9

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

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

还有一种删除评论的方法。

这可能吗?

4

4 回答 4

20

用注释包装元素,或者更具体地说,用具有该元素 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,那么它是一个注释。

例如:

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

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);
    }
});
于 2013-03-21T19:03:03.067 回答
3

您可以通过执行以下操作将元素注释掉:

function comment(element){
    element.wrap(function() {
        return '<!--' + this.outerHTML + '"-->';
    });
}

演示:http: //jsfiddle.net/dirtyd77/THBpD/27/

于 2013-03-21T18:02:40.000 回答
2

我印象深刻,没有人给出以下解决方案。以下解决方案需要一个容器。这个容器里面会有注释/未注释的代码。

function comment(element) {
    element.html('<!--' + element.html() + '-->')
}

function uncomment(element) {
    element.html(element.html().substring(4, element.html().length - 3))
}

function isCommented(element) {
    return element.html().substring(0, 4) == '<!--';
}

示例:https ://jsfiddle.net/ConsoleTVs/r6bm5nhz/

于 2018-08-02T14:39:45.833 回答
-2

为了包装?

function wrap(jQueryElement){
    jQueryElement.before("<!--").after("-->");
}

不确定一旦包装好你会发现评论有多成功。使用正则表达式对 body 元素进行文本搜索是一种选择。

或者这个 -是否可以使用 jquery 从 dom 中删除 html 注释

于 2013-03-21T16:58:53.627 回答