[英]Quick way to replace html comments in javascript
假設您有一個來自服務器的帶注釋的html結構(對它進行注釋以提高渲染速度,例如FB)。 之后,我們應刪除內容並允許瀏覽器呈現html。 最快的方法是什么?
可能使用jQuery取消注釋插件
您可以使用“ 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插件:
好得到評論的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.