我正在寻找一种方法,用jQuery将一个元素包装到注释中,如:
<!--
<div class="my_element"></div>
-->
还有一种删除评论的方法。
这可能吗?
要使用注释包装元素,或者更具体地用具有该元素的HTML的注释节点替换元素:
my_element_jq = $('.my_element');
comment = document.createComment(my_element_jq.get(0).outerHTML);
my_element_jq.replaceWith(comment);
要切换回来:
$(comment).replaceWith(comment.nodeValue);
如果您没有对comment节点的引用,那么您需要遍历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);
}
});
您可以通过执行以下操作来注释元素:
function comment(element){
element.wrap(function() {
return '<!--' + this.outerHTML + '"-->';
});
}
但是:ぁzxswい
我印象深刻,没有人给出以下解决方案。以下解决方案需要一个容器。这个容器将包含内部的注释/未注释代码。
http://jsfiddle.net/dirtyd77/THBpD/27/
示例: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/
不知道你曾经找到评论的成功程度。使用正则表达式对body元素进行文本搜索是一种选择。
或者这个 - function wrap(jQueryElement){
jQueryElement.before("<!--").after("-->");
}