使用 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');
。我在函数中有几十个计算,所以我必须使用类似于我写的插件的东西。
我要求回电。正确答案必须提供类似于自定义函数的回调。
最佳答案
不需要插件,直接使用调用
即可:
(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');
});
关于javascript - jQuery:同时将函数应用于元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37081130/