[英]jquery - is it better to apply a method to a set of DOM elements using filter() or each()
Let's say I have a page that shows a default set of DOM elements on page load, and once the page loads, I want to go in and hide certain elements.假设我有一个页面,它在页面加载时显示一组默认的 DOM 元素,一旦页面加载,我想进入并隐藏某些元素。
<div id="container">
<ul>
<li id="blue">BLUE</li>
<li id="red">RED</li>
<li id="green">GREEN</li>
<li id="orange">ORANGE</li>
<li id="violet">VIOLET</li>
<li id="teal">TEAL</li>
<li id="black">BLACK</li>
</ul>
</div>
var valid = ['red', 'green', 'blue'];
var $colors = $('li');
$colors
.hide()
.filter(function() {
return valid.includes(this.id);
})
.show();
var valid = ['red', 'green', 'blue'];
var $colors = $('li');
$colors.show();
$colors.each(function() {
if(!valid.includes(this.id) {
$(this).hide();
}
});
Assuming the "real" use case has thousands of colors, which JavaScript approach would be the more efficient?假设“真实”用例有数千种颜色,哪种 JavaScript 方法更有效?
Neither.两者都不。 Loop through the IDs and show them.
循环遍历 ID 并显示它们。
$colors.hide();
valid.forEach(id => $(`#${id}`).show());
Or you can create a single selector by combining all the IDs in valid
:或者,您可以通过组合
valid
所有 ID 来创建单个选择器:
$colors.hide();
valid_selector = valid.map(id => `#${id}`).join(',');
$(valid_selector).show();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.