Javascript 替换textarea脚本中的文本+;RTE

Javascript 替换textarea脚本中的文本+;RTE,javascript,replace,textarea,rte,Javascript,Replace,Textarea,Rte,我有一个javascript代码,可以替换在文本区域中编写的一些单词。如果我写“狗”这个词,它会把它改成“猫”这个词 函数changeText(){ dt=document.getElementsByTagName(“textarea”)[0]; dt.value=dt.value.replace(/dog/g,“cat”); dt.value=dt.value.replace(/blue/g,“red”); dt.value=dt.value.replace(/good/g,“bad”);

我有一个javascript代码,可以替换在文本区域中编写的一些单词。如果我写“狗”这个词,它会把它改成“猫”这个词


函数changeText(){
dt=document.getElementsByTagName(“textarea”)[0];
dt.value=dt.value.replace(/dog/g,“cat”);
dt.value=dt.value.replace(/blue/g,“red”);
dt.value=dt.value.replace(/good/g,“bad”);
}

这个脚本有两个问题,我不知道如何解决

  • 如何调用外部文件以替换文字?我将有200多个字,这将更好,我有他们在单独的文件
  • 如何实现一些简单的RTE(如Nicedit)并且仍然有工作脚本?我试过了,但脚本不起作用
  • 提前感谢您的帮助!:)

  • 由于安全原因,您的可能性有限。最好的方法是使用AJAX技术从服务器加载txt/json/xml文件。请记住,它是一种异步方法。没有JQuery(最流行的JS库),使用纯Javascript,您可以通过以下代码实现:

    var fileContent = '';
    var client = new XMLHttpRequest(); // we create a request
    client.open('GET', '/foo.txt'); // foo.txt is the name of the file
    client.onreadystatechange = function() {
      fileContent = client.responseText;
      alert("Hooray! My file was loaded, this is its content: " + fileContent );
    }
    client.send(); // and we send a request
    
  • 每个富文本编辑器都有自己的JS库和获取编辑器内容的方法,所以这要视情况而定。对于nicedit,它是这样的(假设您的textarea有一个ID):

  • var fileContent = '';
    var client = new XMLHttpRequest(); // we create a request
    client.open('GET', '/foo.txt'); // foo.txt is the name of the file
    client.onreadystatechange = function() {
      fileContent = client.responseText;
      alert("Hooray! My file was loaded, this is its content: " + fileContent );
    }
    client.send(); // and we send a request
    
    var nicInstance = nicEditors.findEditor('idOfYourTextarea');
    var notes = nicInstance.getContent(); // voila - your content