在网页中查找“旧”的所有实例,并使用javascript bookmarklet将每个实例替换为“new” [英] Find all instances of 'old' in a webpage and replace each with 'new', using a javascript bookmarklet

查看:136
本文介绍了在网页中查找“旧”的所有实例,并使用javascript bookmarklet将每个实例替换为“new”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是用JS书签或者creammonkey脚本中的'new'替换网页中'old'的所有实例。我怎样才能做到这一点?我认为jQuery或其他框架是可以的,因为它们都包含在bookmarklet和greasemonkey脚本中。

What I want to do is replace all instances of 'old' in a webpage with 'new' in a JS bookmarklet or a greasemonkey script. How can I do this? I suppose jQuery or other frameworks are okay, as there're hacks to include them in both bookmarklets as well as greasemonkey scripts.

推荐答案

一个防止破坏的功能。这意味着这不会触及任何标签或属性,只会触及文本。

A function that is clobber-proof. That mean's this won't touch any tags or attributes, only text.

function htmlreplace(a, b, element) {    
    if (!element) element = document.body;    
    var nodes = element.childNodes;
    for (var n=0; n<nodes.length; n++) {
        if (nodes[n].nodeType == Node.TEXT_NODE) {
            var r = new RegExp(a, 'gi');
            nodes[n].textContent = nodes[n].textContent.replace(r, b);
        } else {
            htmlreplace(a, b, nodes[n]);
        }
    }
}

htmlreplace('a', 'r');

Bookmarklet版本:

Bookmarklet version:

javascript:function htmlreplace(a,b,element){if(!element)element=document.body;var nodes=element.childNodes;for(var n=0;n<nodes.length;n++){if(nodes[n].nodeType==Node.TEXT_NODE){nodes[n].textContent=nodes[n].textContent.replace(new RegExp(a,'gi'),b);}else{htmlreplace(a,b,nodes[n]);}}}htmlreplace('old','new');

这篇关于在网页中查找“旧”的所有实例,并使用javascript bookmarklet将每个实例替换为“new”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆