Dom元素更新,而不使用javascript清除innerHtml



假设我的HTML中有以下购物列表。

<html>
<body>
<ul>
<li> Milk items 2 </li>
<li> Veg item 4 </li>
<li> Eggs 5 crates </li>
</ul>
<button id="double">double</button>
</body>
</html>

现在我想将每个项目的数量增加一倍,一种方法是清除ul的innerHtml,然后重新放入适当的数据。还有别的办法吗?如果是,请描述。如果不是,那么如果我们有数百万个列表项(仅用于教育目的(,这种方法是否有效。谢谢,

您可以将数量attribute添加到项目中,并将li中的数字包装到span中。然后将CCD_ 4乘以2并更新每个li>spanHTML

// Get the button and the list
var btn = document.getElementById('double');
var list = document.querySelector('.list');
// Add event (click) to the button
btn.addEventListener('click', () => {
// Get the items in the list 
var li = list.querySelectorAll('li');

for(var i = 0; i < li.length; i++){
// Get the quantity attribute of each item 
var quantity = parseInt(li[i].getAttribute('quantity'));
// Get the span of each item and update the HTML = quantity multiplied by two
li[i].querySelector('span').innerHTML = quantity * 2;
}
});
<ul class="list">
<li quantity="2"> Milk items <span>2</span> </li>
<li quantity="4"> Veg item <span>4</span> </li>
<li quantity="5"> Eggs <span>5</span> crates </li>
</ul>
<button id="double">Double</button>

最新更新