简体   繁体   English

立即用Javascript更新DOM元素

[英]Update DOM Elements Immediately in Javascript

For a simple project, I'm trying to display log output in a textarea. 对于一个简单的项目,我正在尝试在文本区域中显示日志输出。 I have a log function, and would like the textarea to always be updated immediately whenever log is called. 我有一个log功能,并且希望textarea总是在每次调用log立即更新。 Unfortunately, it seems to only do the update once, and push everything at the same time (I'm using JQuery to set the value of the textarea, if that possibly matters). 不幸的是,它似乎只执行一次更新,并同时推送所有内容(如果可能的话,我正在使用JQuery设置textarea的值)。 Here's a basic example: 这是一个基本示例:

for (i = 0; i <= 100; i++) {
    $("textarea").html($("textarea").html() + "test" + i + "\n");
    $("textarea").scrollTop(9999999)
};

This spits out all the text into the textarea at once (note: you can see the results of these examples at this jsfiddle ). 这会将所有文本立即吐出到textarea中(注意:您可以在jsfiddle上看到这些示例的结果)。 This basic example is easily remedied by creating a timeout and using recursive function calls: 通过创建超时并使用递归函数调用,可以轻松地纠正此基本示例:

f = function(i) {
    if (i <= 100) {
        $("textarea").html($("textarea").html() + "test" + i + "\n");
        $("textarea").scrollTop(999999);
        setTimeout(function() { f(i+1); }, 0);
    }
};

f(1);

This version spits out the text into the textarea one line at a time, which is what I want. 这个版本一次将文本吐出到文本区域中,这正是我想要的。 But using timeouts and callbacks in this manner does not seem practical in the setting of logging; 但是以这种方式使用超时和回调在日志记录设置中似乎不切实际。 every time I call log , I would have to provide a callback for all the functionality that I want to ever follow the log call. 每次调用log ,我都必须为要在log调用之后使用的所有功能提供回调。

Is there any way to achieve the desired effect without callbacks? 有没有办法在没有回调的情况下达到预期的效果?

I think you might consider using : 我认为您可以考虑使用:

$("textarea").val(function(index, value) {
   return value + "test" + i + "\n"
});

instead of : 代替 :

$("textarea").html($("textarea").html() + "test" + i + "\n");

or in general : 或一般而言:

$("textarea").val(NEWVAL)

Also noted in the comments of your question , if you want to be able to notice "by eye" all the messages that arrives you'll have to save them in a buffer and have something like (not tested) : 在问题的注释中也已指出 ,如果您希望能够“目睹”所有到达的消息,则必须将它们保存在缓冲区中,并具有类似(未经测试)的内容:

var buffer = []

function log(text) { buffer.push(text) }

setInterval(function(){
  if (len(buffer)>0) {
    $("textarea").val(function(index, value) {
      return value + "\n" + buffer.shift()
    });
  }
},500)

浏览器通常(Opera是一个例外)在同一线程上执行JS执行和渲染,因此,当您的JS运行时,浏览器将不会进行渲染,除非您通过超时或间隔计时器明确地屈服于控制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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