[英]Js jquery recursive function
I want to make a recursive function. 我想做一个递归函数。 Consider I have a function named setoptions and I need to set 2 options so what I will do is call my function twice like this. 考虑一下我有一个名为setoptions的函数,我需要设置2个选项,因此我要做的是这样两次调用我的函数。
setoptions ("ajax",true);
setoptions ("lamda",false);
So to avoid it I should be able to write a function in a way that I can define multiple options like 因此,为了避免这种情况,我应该能够以可以定义多个选项的方式编写函数,例如
setoptions({
"lamda": false,
"ajax": true
});
This is same as jquery`s attr function. 这与jquery的attr函数相同。 like 喜欢
$("#ff").attr("href","#");
$("#ff").attr("data-type","blue");
// can be used as
$("#ff").attr({
"data-type": "blue",
"href": "#"
});
Kindly do not provide workarounds as I need to understand such recursion for learning. 请不要提供解决方法,因为我需要了解这种递归进行学习。
Basic setOption function: 基本的setOption函数:
var setOption = function (val1, val2) {
$.someplugin(val1, val);
};
Try this: 尝试这个:
function setOption(){
if(arguments.length==2)
window.arguments[0] = arguments[1];
else {
for(var key in arguments[0]){
setOption(key,arguments[0][key];
}
}
}
Edit: I used window object, because I dunno where your values have to be set. 编辑:我使用窗口对象,因为我不知道必须在哪里设置您的值。 So you might have to modify the if body statement in your code. 因此,您可能必须在代码中修改if主体语句。
Edit2: As only this is can be called a recursion for me, this would be my approach. Edit2:因为对我来说,这只能称为递归,所以这就是我的方法。 If you want to call a plugin, then I'd design that plugin to act recursively. 如果您想调用一个插件,那么我将设计该插件以递归方式进行操作。
* EDIT 3 * Yeah I think something like this. * 编辑3 *是的,我认为是这样。 Do note that it is still not recursive.console.log() line should not repeat. 请注意,它仍然不是递归的。console.log()行不应重复。
var setOption = function () {
if (arguments.length == 2) {
console.log(arguments[0], arguments[1]);
} else if (jQuery.isPlainObject(arguments[0])) {
for (var key in arguments[0]) {
console.log(key, arguments[0][key]);
}
}
}
//USAGE:
setOption({
"href": "#",
"data": "123",
});
setOption("cell", true);
} }
Try with: 尝试:
var setOption = function (data) {
for (var key in data) {
$.someplugin(key, data[key]);
}
};
This is I came up with. 这是我想出的。 Let me know if there is a better approach. 让我知道是否有更好的方法。 This is now true recursive. 现在这是真正的递归。
var setOption = function () {
if (jQuery.isPlainObject(arguments[0])) {
for (var key in arguments[0]) {
setOption(key, arguments[0][key]);
}
} else if (arguments.length == 2) {
console.log(arguments[0], arguments[1]);
}
}
//USAGE:
setOption({
"href": "#",
"data": "123",
});
setOption("cell", true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.