繁体   English   中英

用javascript替换文档中的特定文本?

[英]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。

更新:

根据您的评论,我对其进行了测试并成功运行,您可以在此处查看:

http://jsbin.com/odipu3

document.write是不良的做法。

(您要替换的)文本是否存在于文档中的多个位置? 进行此文本替换的正确方法是遍历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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM