jQuery注释/取消注释
我正在寻找一种方法,用jQuery将一个元素包装到注释中,如:
<!-- -->
还有一种删除评论的方法。
这可能吗? 因为我找不到任何相关的东西。
要使用注释包装元素,或者更具体地用具有该元素的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那么它是一个注释。
例如:
bar bar
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 ''; }); }
演示: http : //jsfiddle.net/dirtyd77/THBpD/27/
我很生气没有人给出以下解决方案。 以下解决方案需要一个容器。 这个容器将包含内部的注释/未注释代码。
function comment(element) { element.html('') } function uncomment(element) { element.html(element.html().substring(4, element.html().length - 3)) } function isCommented(element) { return element.html().substring(0, 4) == '
包装?
function wrap(jQueryElement){ jQueryElement.before(""); }
不知道你曾经找到评论的成功程度。 使用正则表达式对body元素进行文本搜索是一种选择。
或者这个 – 是否可以使用jquery从dom中删除html注释
Interesting Posts