2010-07-29 50 views
1

我無法得到這個工作... ...它只是與結果替換整個頁面用javascript替換文檔中的特定文本?

var str="textiwanttoreplace"; 
var el = document.getElementById('welcome'); 
el.innerHTML = str; 
var date = new Date(); 
var hours = date.getHours(); 


if (hours >= 8 && hours < 13) { 
    el.innerHTML = str.replace("textiwanttoreplace", "It's 8 and 13"); 
} else if (hours >= 13 && hours < 18) { 
    el.innerHTML = str.replace("textiwanttoreplace", "It's 13 and 18"); 
} else if (hours > 18 && hours <= 23) { 
    el.innerHTML = str.replace("textiwanttoreplace", "It's 18 and 23"); 
} else { 
    el.innerHTML = str.replace("textiwanttoreplace", "Hello"); 
} 

編輯:改變,現在我沒有看到任何結果我失去了什麼?

回答

2

It would,如果你要替換文本並在頁面的某一部分地說,你應該去了解這樣的事情:

var str="textiwanttoreplace"; 
var el = document.getElementById('element_id'); 
el.innerHTML = str; 

所以不是:

document.write(); 

使用:

var el = document.getElementById('element_id'); 
el.innerHTML = str.replace("textiwanttoreplace", "Good Morning"); 

只需將element_id替換爲要放置文本結果的元素的ID。

更新:基於您的評論

,我測試了它和它的作品,你可以看看這裏:

http://jsbin.com/odipu3

+0

改成這樣,但我似乎無法得到它的工作。我錯過了什麼?(問題中的新代碼) – kevin 2010-07-29 19:33:59

+0

@kevin:請參閱我更新的答案。 – Sarfraz 2010-07-29 19:39:55

+0

真棒,工作感謝 – kevin 2010-07-29 19:58:56

1

document.write is BAD practice.

是否文本(即你想替換)存在於文檔中的多個位置?做這種文本替換的正確方法是遍歷DOM並替換包含所述文本的特定元素的文本內容。

+0

不僅一次,我會怎麼做?談到JavaScript時,我多多少少都是一個noob – kevin 2010-07-29 19:34:26

0

您需要縮小要替換的文本的父級。你可以對整個文檔做這件事,但效率極低。

<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $("div.replace-me").text($(this).text().replace('will replace', 'Good morning')); 
    }); 
</script>