0

以下是我的用户脚本。它不会发出警报,因为当我替换 html 时,我会以某种方式破坏它。

如何替换 div 或 span 中的常规文本,即 domain[dot]com,使其显示为 domain.com?好吧,下面的工作但会破坏运行后的代码和其他用户脚本。

$(function() {
    var html = $('body').html();
    var res=html.replace(/\[dot\]/g, ".");
    $('body').html(res);
    //doesnt call, however html is replaced
    alert('a'); 
});
4

2 回答 2

2

替换页面中的文本,而不是替换整个 HTML。如果您获取整个 HTML 并将其放回原处,这将使其重新解析所有代码并将其放回最初加载时的状态,这意味着绑定到任何元素的任何事件都消失了。

使用递归函数查找文档中的文本节点并对每个节点中的文本进行替换:

function replaceText(node, replacer) {
  var n = node.childNodes;
  for (var i = 0; i < n.length; i++) {
    if (n[i].nodeType == 3) {
      n[i].nodeValue = replacer(n[i].nodeValue);
    } else {
      replaceText(n[i], replacer);
    }
  }
}

$(function(){

  replaceText(document.body, function(s){
    return s.replace(/\[dot\]/g, '.');
  });

});

演示:http: //jsfiddle.net/Guffa/ex83P/

As you see, there is no jQuery in the function, because jQuery only deals with elements, there are no methods to deal with text nodes.

于 2012-10-07T11:59:18.517 回答
0

Is this for a specific set of pages or do you plan on doing this across every page you encounter? If specific, try narrowing down your selectors significantly. This way you're not trying to process every span/div on the page (which is obv slow). Firebug should be able to help you.

于 2012-10-07T12:44:46.153 回答