JavaScript加载程序,同时更新多个表行内容

时间:2019-04-18 21:16:37

标签: javascript jquery loops promise

我想在需要一段时间的操作中显示加载程序,并在完成后隐藏它。我的代码只是遍历所有表行(大约2000行)并更新其单元格中的内容。

问题在于,此加载程序显示的调用不会在代码执行之前触发,因此不会显示加载程序。

$('#loader').fadeIn();

const $rows = $('.rows:checked');

for (let i = 0; i < $rows.length; ++i) {
  const id = $rows[i].dataset.productId;
  const $text = document.getElementById(`text-${id}`);
  const $value = document.getElementById(`value-${id}`);

  $value.textContent = value;
  $text.textContent = text;
}

return $('#loader').fadeOut();

我希望加载器在循环开始之前显示,并在循环结束后隐藏。

1 个答案:

答案 0 :(得分:1)

我看到您正在尝试在完成操作之前或之前返回加载程序。您可以使用promise来告诉函数何时完成隐藏加载程序。然后将加载程序包装在一个函数中,以根据是非值显示或隐藏它。

这样的事情。

=INDEX($A$1:$I$9,MATCH($N2,$C$1:$C$9,0),MATCH(O$1,$A$1:$I$1,0))

本质上会这样做

function loader(show) {
    if (show) {
        // True, we show loader
        $('#loader').fadeIn();
    } else {
        // Was loader(false) we hide it
        $('#loader').fadeOut();
    }
}

function start() {
    loader(true); // Show loader
    return new Promise((resolve) => {
        for (let i = 0; i < $rows.length; ++i) {
            const id = $rows[i].dataset.productId;
            const $text = document.getElementById(`text-${id}`);
            const $value = document.getElementById(`value-${id}`);

            $value.textContent = value;
            $text.textContent = text;
        }
      resolve() // Resolve
    })
}
// Run start() function then wait until it resolves(), finishes to do something
start().then(() => {
    // Our loop finished
    loader(false) // Hide loader
})
function loader(b) {
   if (b) {
      console.log('Showing loader');
   } else {
      console.log('Hiding loader');
   }
}

function start() {
    loader(true);
    return new Promise((resolve, reject) => {
         console.log('Start()');
         resolve();
         // We also could use reject() for error handling
    })
}

let start_button = document.getElementById('start_button');
start_button.onclick = function() {
    start().then(() => {
         console.log('Function resolved and finished');
         loader(false);
    }).catch((error) => {
         // If we use reject()
    })

}

相关问题