javascript 刷新文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14479798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript flush text
提问by Refael
I'm trying to change the text in an h3
tag, but the changes don't happen until that the function is ended. I want to change the text immediately.
我正在尝试更改h3
标签中的文本,但直到函数结束后才会发生更改。我想立即更改文本。
For example:
例如:
<h3 id="myText"></h3>
<input type="button" onClick="changeText('Hello');">
<script type="text/javascript">
function changeText(str){
document.getElementById('myText').innerHTML = str;
}
</script>
Is it possible to refresh the screen immediately after changing the text?
(Like flush()
command in C).
更改文本后是否可以立即刷新屏幕?(就像flush()
C 中的命令一样)。
Note that if I put an alert
after the command, the text is changed immediately:
请注意,如果我alert
在命令后放置一个,文本会立即更改:
function changeText(str){
document.getElementById('myText').innerHTML = str;
alert('HelloWorld');
}
回答by Denys Séguret
To force an immediate refresh, you can do this :
要强制立即刷新,您可以这样做:
document.getElementById('myText').innerHTML = str; // change the dom
setTimeout(function(){
// do other things
}, 0);
The do other things
code will be executed after the refresh.
该do other things
代码将刷新后执行。
But it's highly unusual to have a script go on running for seconds.
但是让脚本持续运行几秒钟是非常不寻常的。
回答by Felipe Oriani
If you are talking about the refresh all the page, you will lose the content you have changed on the client side because it is stateless (between requests). If you persist it on a repository (session, application, files you can read and write, databases, etc..) on server side you can read from the server side and keep it on your html elements.
如果您正在谈论刷新所有页面,您将丢失在客户端更改的内容,因为它是无状态的(在请求之间)。如果您将它保存在服务器端的存储库(会话、应用程序、您可以读写的文件、数据库等)上,您可以从服务器端读取并将其保存在您的 html 元素中。
In Javascript you could implement an dictionary (element id on key and innerHTML on value) and use it as a cache and implement a flush method to display all changes, try something like:
在Javascript中,您可以实现一个字典(键上的元素id和值上的innerHTML)并将其用作缓存并实现刷新方法来显示所有更改,请尝试以下操作:
<script>
var cacheChanges = {};
function addChange(element, value){
cacheChanges[element] = value;
}
function flush() {
for(var i in cacheChanges)
{
var element = document.getElementById(i);
if (element) {
element.innerHTML = cacheChanges[i];
}
}
}
function ChangeSomething(){
// do some changes
addChange('myText', 'Hello');
addChange('myText2', 'Hello 2');
addChange('myText3', 'Hello 3');
// apply all them
flush();
}
</script>
and in your html:
并在您的 html 中:
<h3 id="myText"></h3>
<h3 id="myText2"></h3>
<h3 id="myText3"></h3>
<input type="button" onClick="ChangeSomething();">