JavaScript:如何将多个参数传递给对象成员内部的回调函数? [英] JavaScript: How to pass multiple arguments to a callback function inside an object's member?
问题描述
在使用插件时,有时会偶然发现一个类似这样的插件:
When working with plugins I sometimes stumble upon one that has something like this:
- 它将使用构造函数参数.
- 某些参数解析为函数.
- 其中一些会引起多种争论.
像这样:
{
color: function (someData, moreData) {
return someData + moreData;
}
}
如何向该函数传递两个参数?
注意:我无法更改插件,因此不能将第二个参数移至另一个构造函数参数.
Note: I am unable to change the plugin, so moving the second argument to another constructor argument is not an option.
示例JavaScript:
Sample JavaScript:
(function ($) {
$.fn.greenify = function (options) {
var settings = $.extend({
color: function (someData, moreData) { // <-- THIS TAKES 2 ARGUMENTS!
return someData + moreData;
},
}, options);
return this.css({
color: settings.color,
});
};
}(jQuery));
$("#target1").greenify({
color: "blue"
});
$("#target2").greenify({
color: ["bl", "ue"] // <-- In your answer only this should be changed
});
我的目标:
<div id="target1">My Thing</div> // <-- will be blue
<div id="target2">My Thing2</div> // <-- will be black but should be blue
更新: 我对这个代码
$("#target1").greenify({
color: "blue"
});
会将值"blue"
作为第一个参数someData
传递给function (someData, moreData)
. 这是错误的! 实际上发生的是默认回调(function (someData, moreData)
)被字符串"blue"
完全替换了!
would hand the value "blue"
over to function (someData, moreData)
as first parameter someData
. This is false! What actually happens is that the default callback (function (someData, moreData)
) is completely replaced by the string "blue"
!
推荐答案
如何将两个参数传递给该函数?
How do I pass two arguments to that function?
你不知道. jQuery确实如此.它是一个回调函数,可在.css()
方法中动态确定color
属性-请参见
You don't. jQuery does. It's a callback function to determine the color
property dynamically in the .css()
method - see the docs.
因此,实际上,该默认函数没有任何意义,因为它应该返回css颜色值,但返回以元素索引为前缀的旧值-绝对不是颜色.
So actually, that default function doesn't make any sense as it should return a css color value but returns the old value prefixed by the index of the element - which is definitely not a color.
所以只需使用$("#target2").greenify({color: "black"})
.
如果您想传递一个函数,那也是可以的-但是它将覆盖,而不是调用该默认函数.一个例子:
If you want to pass a function, that is also possible - but it will overwrite, not call that default function. An example:
$("div").greenify({
color: function(index, prevColor) {
return ["blue", "black"][index % 2];
}
});
这篇关于JavaScript:如何将多个参数传递给对象成员内部的回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!