簡體   English   中英

在JavaScript中替換HTML注釋的快速方法

[英]Quick way to replace html comments in javascript

假設您有一個來自服務器的帶注釋的html結構(對它進行注釋以提高渲染速度,例如FB)。 之后,我們應刪除內容並允許瀏覽器呈現html。 最快的方法是什么?

您可以使用“ content()”方法對所有節點進行注釋,包括注釋:light和plugin free!

然后,您應該使用“ 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);
    });
}
$(stringHtml).comments().remove();

...使用jquery-comments插件:

http://www.bennadel.com/blog/1563-jquery-comments-plug-in-to-access-html-comments-for-dom-templating.htm

好得到評論的DOM,然后執行replace()

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

試試這個方法。 為元素節點提供帶注釋的HTML,這將刪除注釋塊並顯示HTML。

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

如果您的注釋HTML在注釋開始/結束標記中具有三個或更多破折號(<-/ <---),請確保更新上述函數中的replace()表達式。

這是一個JSFIDDLE,可以提供更好的解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM