2016-03-15 120 views
0

我有一个JavaScript代码,用于替换文字区域中的某些字词。例如。如果我写“狗”字,它会将其改为“猫”字。替换textarea脚本中的文本+ RTE

<html> 
<head> 
<script> 
function 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"); 
} 
</script> 
</head> 
<body> 
<textarea rows="10" cols="65"></textarea> <br> 
<input type="button" value="change" onclick="changeText()"> 
</body> 
</html> 

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

  1. 如何使用文字调用外部文件进行替换?我会有200多个单词,我最好将它们放在单独的文件中。
  2. 如何实现一些简单的RTE(例如Nicedit)并且仍然有工作脚本?我试试看,脚本不起作用...

在此先感谢您的帮助! :)

回答

0
  1. 由于安全原因,您的可能性是有限的。最好的方法是使用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 
    
  2. 每一个富文本编辑器都有自己的JS库和一种方式来获得编辑的内容,所以它真的依靠。对于nicedit是这样的(假设你的textarea有一个ID):

    var nicInstance = nicEditors.findEditor('idOfYourTextarea'); 
    var notes = nicInstance.getContent(); // voila - your content