简体   繁体   English

javascript查找并替换整个文档

[英]javascript find and replace over whole document

What is the easiest way to make string replacement in whole document using a table of replacement? 使用替换表在整个文档中进行字符串替换的最简单方法是什么? I mean having a list of pairs of old and new values to make replacement of all strings in the document (but not the values of input or select elements). 我的意思是拥有一对新旧值列表,以替换文档中的所有字符串(而不是输入或选择元素的值)。

Try something like this (Remember to add jQuery first): 尝试这样的事情(请记住首先添加jQuery):

$(document).ready(function(){
    $("body").children().each(function(){
        var $this = $(this);
        if($this.prop("tagName").toLowerCase() == "input" || $this.prop("tagName").toLowerCase() == "select"){
            continue;
        }
        else if($this.text() == "hello"){
            $this.text("Bye");
        }
    });
});

If you also want to store a record for older values you can do something like this: 如果您还想存储旧值的记录,可以执行以下操作:

$(document).ready(function(){
    var older_values = [];
    $("body").children().each(function(){
        var $this = $(this);
        if($this.prop("tagName").toLowerCase() == "input" || $this.prop("tagName").toLowerCase() == "select"){
            continue;
        }
        else if($this.text() == "hello"){
            older_values.push($this.text());
            $this.text("Bye");
        }
    });
});

* Edit * To grab all the elements inside the body tag, just replace the: *编辑*要获取body标签内的所有元素,只需替换:

$("body").children()

with

$("body").find("*")

Hope that works for you 希望对你有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM