我有一个想要实现的全选按钮。哪种方式更快?
$('.check-box').prop('disabled', false).trigger('change');
或者
$('.check-box').each(function(index, element){
$(element).prop('disabled', false).trigger('change');
});
在用户界面中他们做同样的事情。 看起来第二个不仅按类名选择,而且还选择每个元素,这是一个 O(MN) 操作。但是第一种方法是否有可能只是在幕后执行第二种方法所做的事情(尽管这将使第一种方法更有利,因为它的代码更少,加载时间更快)?
最佳答案
大多数 jQuery 方法都有一个内部 each
,基本上看起来像:
// $.fn is where chainable methods reside
$.fn.methodName = function(){
// "this" is the jQuery object that contains collection of elements
// returned by either $(selector) or prior method in chain
// return "this" for chaining and loop over all elements in collection
return this.each(function(){
// "this" is individual element instance
// do same thing to each element here
});
}
这就是 $('.check-box').prop('disabled', false).trigger('change');
将如何影响 class= 的所有元素“复选框”
关于javascript - jQuery 中更改 JS 元素集合的哪种方式更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55545491/