【问题标题】:How do I update the html displayed for each iteration of a for loop in javascript / jquery?如何更新为 javascript / jquery 中的 for 循环的每次迭代显示的 html?
【发布时间】:2013-02-13 22:28:48
【问题描述】:

如何为循环的每次迭代更改 h1?这段代码现在只在一切完成后显示 h1 文本。

for (i=0; i<array.length; i++) {
  $("body > h1").text("Processing #" + i);
  // things that take a while to do
}

附加信息:如果我在循环时调整窗口大小,则 html 会更新。

【问题讨论】:

  • 在您将控制权交还给它之前,浏览器不会呈现。这意味着在您退出 for 循环之前它不会呈现。但通常有一些技巧可以强制它重新渲染。虽然我真的建议你重写你的循环,让浏览器每次迭代都让步,然后继续……这样窗口就不会锁定在用户身上。
  • "虽然我真的建议您重写循环以在每次迭代中让给浏览器并在之后继续" 我该怎么做?谢谢。
  • 我在答案中添加了一个示例。

标签: javascript jquery html loops iteration


【解决方案1】:

如果过程很长,您可以使用此脚本显示特定时间间隔内的每个通知。

这里是代码..

html

<div id="ccNotificationBox"></div>

css

#ccNotificationBox{
 -webkit-animation-name:;
 -webkit-animation-duration:2s;/*Notification duration*/
 box-sizing:border-box;
 border-radius:16px;
 padding:16px;
 background-color:rgba(0,0,0,0.7);
 top:-100%;
 right:16px;
 position:fixed;
 color:#fff;
}
#ccNotificationBox.active{
 -webkit-animation-name:note;
 top:16px;
}
@-webkit-keyframes note{
0%   {opacity:0;}
20%  {opacity:1;}
80%  {opacity:1;}
100% {opacity:0;}
}

javascript

var coccoNotification=(function(){
var
nA=[],
nB,
rdy=true;
function nP(a){
 nA.push(a);
 !rdy||(nR(),rdy=false);
}
function nR(){
 nB.innerHTML=nA[0];console.log(nA[0]);
 nB.offsetWidth=nB.offsetWidth;//reflow ios
 nB.classList.add('active');
}
function nC(){
 nB.classList.remove('active');
 nB.innerHTML='';
 nA.shift();
 nA.length>0?nR():(rdy=true);
}
function init(){
 nB=document.getElementById('ccNotificationBox');
 nB.addEventListener('webkitAnimationEnd',nC,false);
 window.removeEventListener('load',init,false);
}
window.addEventListener('load',init,false);
return nP
})();

用法

coccoNotification('notification 1');

示例

http://jsfiddle.net/f6dkE/1/

信息

上面的例子非常适合外部 js,因为你只使用了一个全局变量,它是函数的名称......在我的例子中是 coccoNotification

这是一种不同的方法,但它的作用是一样的

http://jsfiddle.net/ZXL4q/11/

【讨论】:

    【解决方案2】:

    DEMO

    我花了一些时间来设计一个似乎可以解决这个问题的 jquery 函数。基本上,它是一个进程处理程序,您可以add 任意数量的进程,然后调用run 以异步方式顺序调用它们。

    $.fn.LongProcess = function () {
        var _this = this;
        this.notifications = [];
        this.actions = [];
    
        this.add = function (_notification, _action) {
            this.notifications.push(_notification);
            this.actions.push(_action);
        };
        this.run = function () {
    
            if (!_this.actions && !_this.notifications) {
                return "Empty";
            }
            //******************************************************************
            //This section makes the actions lag one step behind the notifications.
            var notification = null;
            if (_this.notifications.length > 0) notification = _this.notifications.shift();
    
            var action = null;
            if ((_this.actions.length >= _this.notifications.length + 2) || (_this.actions.length > 0 && _this.notifications.length == 0)) 
                action = _this.actions.shift();
            //****************************************************************
            if (!action && !notification) {
                return "Completed";
            }
    
            if (action) action();        
            if (notification) notification();
    
            setTimeout(_this.run, 1000); 
            //setTimeout(_this.run,1); //set to 1 after you've entered your actual long running process. The 1000 is there to just show the delay.
        }
        return this;
    };
    

    如何与&lt;h1 class="processStatus"&gt;&lt;/h1&gt;一起使用:

    $(function () {
        var process = $().LongProcess();
    
        //process.add(notification function, action function);
        process.add(function () {
            $(".processStatus").text("process1");
        }, function () {
            //..long process stuff
            alert("long process 1");
        });
    
        process.add(function () {
            $(".processStatus").text("process2");
        }, function () {
            //..long process stuff
            alert("long process 2");
        });
    
        process.add(function () {
            $(".processStatus").text("process3");
        }, function () {
            //..long process stuff
            alert("long process 3");
        });
    
        process.run();
    });
    

    【讨论】:

      【解决方案3】:
      var array = ['one', 'two', 'three']
      var i = 0;
      
      var refreshIntervalId = setInterval(function() {
          length = array.length;
          if (i < (array.length +1)) {
              $("h1").text("Processing #" + i);
          } else {
              clearInterval(refreshIntervalId);
          }
          i++     
      }, 1000);
      

      http://jsfiddle.net/3fj9E/

      【讨论】:

        【解决方案4】:

        有时您可以通过强制重新计算布局来强制渲染

        for (i=0; i<array.length; i++) {
          $("body > h1").text("Processing #" + i)
              .width();  // force browser to recalculate layout
          // things that take a while to do
        }
        

        它可能不适用于所有浏览器。

        一种更好的方法,不会过多地阻塞浏览器:

        function doThings(array) {
           var queueWork,
               i = -1,
               work = function () {
                  // do work for array[i]
                  // ...
                  queueWork();
               };
        
           queueWork = function () {
               if (++i < array.length) {
                  $("body > h1").text("Processing #" + i);
                  setTimeout(work, 0); // yield to browser
               }
           };
        }
        
        
        doThings(yourArray);
        

        【讨论】:

          【解决方案5】:

          使用setInterval 延迟一毫秒:

          var i=0, j=array.length;
          var iv = setInterval(function() {
              $("h1").text("Processing #" + i);
              // things that take a while to do
              if (++i>=j) clearInterval(iv);
          }, 1);
          

          http://jsfiddle.net/mblase75/sP9p7/

          【讨论】:

            猜你喜欢
            • 2020-02-27
            • 2020-07-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-02-10
            • 1970-01-01
            • 2018-02-13
            • 1970-01-01
            相关资源
            最近更新 更多