简体   繁体   English

在JavaScript中替换HTML注释的快速方法

[英]Quick way to replace html comments in javascript

Assume you have a structure of commented html, that comes from server (it's commented for improve rendering speed, like FB). 假设您有一个来自服务器的带注释的html结构(对它进行注释以提高渲染速度,例如FB)。 After that we should remove our content and allow browser render html. 之后,我们应删除内容并允许浏览器呈现html。 What is the quickest way to do this? 最快的方法是什么?

you can use the "content()" method to cet all nodes including comments: light and plugin free !! 您可以使用“ content()”方法对所有节点进行注释,包括注释:light和plugin free!

Then you should filter the collection using "filter()" method 然后,您应该使用“ filter()”方法过滤集合

$container
    .contents()
    .filter(function(){ return this.nodeType == 8; })
    .remove(); // replaceWith()  etc.
function _removeComments(node) {
    if (!node || !node.parentNode) return;

    if (node.nodeType == 8) {
        node.parentNode.removeChild(node);
        return;
    }

    for (var c = node.firstChild; c; ) {
        var n = c.nextSibling;
        _removeComments(c);
        c = n;
    }
}

function removeComments(element) {
    element.each(function() {
        _removeComments(this);
    });
}

好得到评论的DOM,然后执行replace()

  var dom =  $.trim($('#domcontainer').html()).replace('<!--','').replace('-->','');

Try this method. 试试这个方法。 Provide the element node with the commented HTML and this will remove the comment blocks and reveal the HTML. 为元素节点提供带注释的HTML,这将删除注释块并显示HTML。

function uncommentNode(node) {
    var nodestr = node.innerHTML;
    var noderevealHTML =  nodestr.replace(/<!--/ig, '').replace(/-->/ig, ''); // Update expressions here.
    node.innerHTML = noderevealHTML;
}

If your commented HTML has three or more dashes (<-- / <---) in the comment start/end tag, be sure to update the replace() expressions in the function above. 如果您的注释HTML在注释开始/结束标记中具有三个或更多破折号(<-/ <---),请确保更新上述函数中的replace()表达式。

Here's a JSFIDDLE for better explanation. 这是一个JSFIDDLE,可以提供更好的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM