我正在创建一个接受输入选项的jQuery插件,如this link中所述。以下是上述链接中的相同代码
df %>% group_by(year) %>% filter(all(c('a', 'b') %in% stage))
# A tibble: 6 x 2
# Groups: year [2]
# year stage
# <dbl> <fctr>
#1 2000 a
#2 2000 a
#3 2000 a
#4 2000 b
#5 2002 a
#6 2002 b
我也在稍微扩展插件,以便在用户传递回调函数时触发用户功能。因此,该插件演变为以下内容:
(function ( $ ) {
$.fn.greenify = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
color: "#556b2f",
backgroundColor: "white"
}, options );
// Greenify the collection based on the settings variable.
return this.css({
color: settings.color,
backgroundColor: settings.backgroundColor
});
};
}( jQuery ));
当用户这样做时:
(function ( $ ) {
$.fn.greenify = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
color: "#556b2f",
backgroundColor: "white",
onGreenify: function () {} // This is a new option
}, options );
// Greenify the collection based on the settings variable.
var newCss = this.css({
color: settings.color,
backgroundColor: settings.backgroundColor
});
// Execute the function
if (typeof settings.onGreenify == "function") {
settings.onGreenify ();
}
return newCss;
};
}( jQuery ));
然后上面的代码将成功运行并显示消息元素现在为绿色。到控制台。
到目前为止一切顺利。
现在,这是我面临的问题。如何将输入参数传递给var greenifyOptions = {
onGreenify: function () {
console.log("Element is now green.");
}
}
$("#id1").greenify(greenifyOptions);
函数?例如,我想做以下事情:
onGreenify
最终应该显示 Hello John。元素现在是绿色的。到控制台。
但我不知道如何修改以下代码以允许它接受输入参数
var name = "John";
var greenifyOptions = {
onGreenify: function (name) {
console.log ("Hello " + name + ". Element is now green.");
}
}
$("#id1").greenify(greenifyOptions);
请注意,此功能应接受任意数量的输入参数。我无法控制用户需要传递的内容。
我的做法是对的吗?需要修改的代码是什么?
感谢。
答案 0 :(得分:1)
嗨这里是一个简单的demo,但是你的想法有些不好,如果名字是全球的,不需要直接传递......我在想怎么做才能通过一个名字通过元素,由de pluging作为范围 :
(function ( $ ) {
$.fn.greenify = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
color: "#556b2f",
backgroundColor: "white",
onGreenify: function () {} // This is a new option
}, options );
// Greenify the collection based on the settings variable.
var newCss = this.css({
color: settings.color,
backgroundColor: settings.backgroundColor
});
// Execute the function
if (typeof settings.onGreenify == "function") {
//settings.onGreenify ();
settings.onGreenify.call(this, settings.name);
}
return newCss;
};
}( jQuery ));
var name = 'juan'
var greenifyOptions = {
name: 'juaanddd',
onGreenify: function (name) {
console.log("Element is "+name+" now green.");
}
}
$("#id1").greenify(greenifyOptions);