[英]jQuery: apply function to elements at the same time
使用jQuery.each()
,我可以遍歷數組的成員:
// This is NOT what I am looking for.
$('.example a').each(function() {
// do a lot of things here
$(this).css('color', 'red');
});
但是,我需要將一個函數應用於jQuery數組本身,而不是其成員。 所以我寫了一個小插件來做到這一點:
$.fn.all = function( callback ) { return callback.call( this ); }
$('.example a').all(function() {
// do a lot of things here
$(this).css('color', 'red');
});
請注意,在上面的函數中, this
將被設置為元素的集合 - 這是我需要的。
現在我確信jQuery應該有一個優雅的方法來做到這一點,但我沒有在文檔中找到任何東西,或者通過谷歌搜索。
是否可能,如果是,如何在不使用自定義插件的情況下實現這一目標?
更新:我不能做$('.example a').css('color', 'red');
直。 我在函數中有幾十個計算,所以我必須使用與我編寫的插件類似的東西。 我要求回電。 正確答案必須提供類似於自定義函數的回調。
不能
$('.example a').css('color', 'red');
足夠?
您不需要插件,可以直接使用call
:
(function() {
// do a lot of things here
this.css('color', 'red');
}).call($('.example a'));
或者考慮將類似數組的對象作為參數傳遞
(function(arrayLike) {
// do a lot of things here
arrayLike.css('color', 'red');
})($('.example a'));
或者如果您更喜歡jQuery方式
$.each([$('.example a')], function(){
// do a lot of things here
this.css('color', 'red');
});
這將是你想做的事情的直接(jQuery-esque)方式:
var $collection = $('.example a');
$collection.each(function() {
// do a lot of things here
$collection.css('color', 'red');
});
//另一個原因我不喜歡jQuery的each()
。
//但最重要的是,錯誤的參數順序和濫用this
來傳遞當前值/節點
這是我首選的實施方案。 主要是像Array.prototype.forEach()
,以及$.each()
的好部分。
$.fn.forEach = function(fn, scope){
if(scope != null) fn = fn.bind(scope);
for(var i = 0, len = this.length; i < len; ++i)
if(false === fn(this[i], i, this)) break;
return this;
}
你的代碼就像:
$('.example a').forEach(function(node, index, $collection){
//and don't use `$(this)`, since `this` most of the time references `window`
//unless you've bound the function to a scope, or passed one to forEach
var $node = $(node);
$collection.css('color', 'red');
});
這個
$('.example a')
返回匹配元素的集合。 還有這個
$('.example a').css('color', 'red');
將紅色設置為集合中的所有元素。
這就是jQuery的工作原理。
我認為不可能同時進行所有計算,你應該使用線程或webWorker
。 你可以在mdn中獲得更多相關信息。
你可以緩存選擇器,利用$.queue()
var elems = $(".example a"); $.queue(elems, "q", function() { $(this).css("color", "red"); console.log(this) }); $.dequeue(elems, "q")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <div class="example"> <a href="#">a</a> <a href="#">b</a> <a href="#">c</a> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.