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

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

问题描述

我想要做的是用 JS 书签或油脂猴脚本中的新"替换网页中旧"的所有实例.我怎样才能做到这一点?我认为 jQuery 或其他框架都可以,因为有一些技巧可以将它们包含在书签和油脂猴脚本中.

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');

书签版本:

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书签在网页中查找所有“旧"实例并将每个实例替换为“新"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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