javascript - jQuery:同时将函数应用于元素

标签 javascript jquery

使用 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/

相关文章:

javascript - 需要检查与点击元素相关的隐藏输入字段的值(多个同名)

javascript - React componentWillUpdate 被调用两次

jquery - Nodejs 和 Expressjs 发送 ajax post 请求

javascript - jquery settimeout 和 .focus() 一起不能在 firefox 浏览器中工作

jquery - 将多个参数传递给 $.delegate

javascript - 如何创建包含 CDATA 的 xml 元素

javascript - 如何在单击 SELECT 多行时创建一个选项?

javascript - JavaScript 中的内联正则表达式

javascript - 无法使用带有 PageFactory 的 Selenium Java 选择下拉元素

ajax - 取消表单提交时的 JQuery UI 自动完成