2015-06-05 42 views
2

,我的英語首先對不起,我有一個不工作的代碼時我執行它全部替換詞在文檔正文不起作用

<script language="javascript" src="/thecode.js"></script> 

我把thecode.js在頁腳

var msg=document.body.innerHTML; 
for(var i=0;i<msg.length;i++){ 
var tx=document.body[i].innerHTML; 
tx=tx.replace(/dog/ig,'animal'); 
tx=tx.replace(/apple/ig,'fruit'); 
tx=tx.replace(/\[VIdEo\]/ig,'Video'); 
tx=tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com'); 
document.body.innerHTML=tx;} 

我想我不會犯任何錯誤,但是當我執行它時,它不起作用。
感謝您的關注... :)

+0

更換的window.onload沒有必要的for循環....也'document.body的[I]'是錯誤的...刪除了循環和'var tx = document.body.innerHTML;' –

+0

**也不要這樣做,因爲它可以刪除任何以前添加的事件處理程序**(使用腳本添加) –

+0

請注意,使用正則表達式處理HTML [*註定要失敗*](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)以奇怪和意想不到的方式。 – RobG

回答

2

無需重複身體元素
試試這個:

想改變與js的?
我已經使用,使它

function addTitleToSurveyUrls() { 
    var elements = document.getElementsByTagName('a'); 
    for(var el in elements) { 
     var element = elements[el]; 
     var href = element.getAttribute("href"); 
     if(href.indexOf('survey_')>-1) { 
      element.setAttribute('title', 'Some TITLE HERE'); 
     } 
    } 
} 

function replaceBodyElements() { 
    var tx=document.body.innerHTML; 
     tx = tx.replace(/dog/ig,'animal'); 
     tx = tx.replace(/apple/ig,'fruit'); 
     tx = tx.replace(/\[VIdEo\]/ig,'Video'); 
     tx = tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com'); 
    document.body.innerHTML=tx; 
} 

window.onload = function(){ 
    replaceBodyElements(); 
    addTitleToSurveyUrls(); 
    // ... some another operations 
}; 

document.onreadystatechange = function() { 
    var state = document.readyState; 
    if(state == 'complete') { 
     replaceBodyElements(); 
     addTitleToSurveyUrls(); 
    } 
}​ 

我用的onload事件因爲也許文檔具有動態元素等,以便更好地等待,而所有元素得到加載,並改變它。 或者你可以用window.document.onload

+1

哎三江源非常多,它現在的工作...:d –