gpt4 book ai didi

javascript - jQuery 'each' 简写

转载 作者:行者123 更新时间:2023-11-28 11:58:42 25 4
gpt4 key购买 nike

有什么方法可以简化 jquery 的操作吗?或者有没有比下面的代码短的 jquery every 编写替代方案?

$('someElement').each(function () {
functionName('value1', value2)
});
$('anotherElement').each(function () {
functionName('value1', value2)
});
$('andMoreElement').each(function () {
functionName('value1', value2)
});

functionName(foo, element){
//function code here
}

最佳答案

从问题的最新版本开始,所有三个each都使用相同的值,您最好使用逗号系列选择器(如果它们是选择器),或 add 函数(如果不是):

$('someElement, anotherElement, andMoreElement').each(function () {
functionName('value1', value2)
});

functionName(foo, element){
//function code here
}

$('someElement').add('anotherElement').add('andMoreElement').each(function () {
functionName('value1', value2)
});

functionName(foo, element){
//function code here
}

同样,这取决于 'someElement''anotherElement' 等是选择器还是元素。

由于您使用的是立即调用该函数的 each,因此您还可以使用下面的 curry 选项。如果您使用的是 click 或类似的方式,则使用下面的 curry 选项会在计算 value2 时发生变化(从调用函数时到调用函数时)柯里化(Currying)),这可能是理想的或不理想的,具体取决于您的用例。

<小时/>

问题早期版本的答案:

遗憾的是,您不能使用 $.proxyFunction#bind 来实现此目的,因为它们都会更改 this 的值> 在通话中。您可以创建curry function重用调用它的 this:

var slice = Array.prototype.slice;
function curry(f) {
var args = slice.call(arguments, 1); // Copy args after `f`
return function() {
return f.apply(this, args.concat(slice.call(arguments, 0)));
};
}

当您将一个函数和 X 个参数传递给 curry 时,它会返回一个函数,该函数在被调用时将使用原来的 this 值调用原始函数调用时,提供给 curry 的参数,然后提供给调用的任何参数。

然后:

$('someElement').each(curry(functionName, 'foo'));
$('anotherElement').each(curry(functionName, 'otherFoo'));
$('andMoreElement').each(curry(functionName, 'otherFoo'));

functionName(foo){
//function code here
}

或者因为后两个用途具有相同的参数:

$('someElement').each(curry(functionName, 'foo'));
$('anotherElement, andMoreElement').each(curry(functionName, 'otherFoo'));
// Or:
$('anotherElement').add('andMoreElement').each(curry(functionName, 'otherFoo'));

functionName(foo){
//function code here
}

关于javascript - jQuery 'each' 简写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18737666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com