Javascript设置值很多元素很慢

我有一个更改输入值的循环,但找不到任何解决方案来优化该值,因为该循环需要5秒钟以上的时间。

我的循环看起来像这样:

for(let i = 0; i < 50; i++)
{
    const element = document.getElementById(`txt-assembly-${i}`);
    element.value = "40";
}
评论
  • fillum
    fillum 回复

    No, setting value on 50 elements isn't slow, it's near instantanous. Your performance issues must be elsewhere. Try looking at the dev console performance tab in chrome.

    for (let i = 0; i < 50; i++)
      document.querySelector('div').appendChild(document.createElement('input'));
    
    let reset = val => [...document.querySelectorAll('input')]
      .forEach(el => el.value = val);
      
    reset(40);
      
    document.querySelector('button').addEventListener('click', () => reset(Math.random() * 100));
    <button>random</button>
    <div></div>