[英]Replace specific text in the document with 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");
}
編輯:已更改,現在我看不到任何結果是否缺少某些東西?
這會 ,如果你要替換的文本,並把在頁面的某一部分,你應該去是這樣的:
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。
更新:
根據您的評論,我對其進行了測試並成功運行,您可以在此處查看:
(您要替換的)文本是否存在於文檔中的多個位置? 進行此文本替換的正確方法是遍歷DOM並替換包含所述文本的特定元素的文本內容。
您需要縮小要替換文本的父級。 您可以對整個文檔執行此操作,但是效率極低。
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.