我在使它无法正常工作时遇到麻烦...它只是将整个页面替换为结果

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");
}


编辑:已更改,现在我看不到任何结果是否缺少某些东西?

最佳答案

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

关于javascript - 用javascript替换文档中的特定文本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3366050/

10-11 23:04
查看更多