[英]jQuery newbie: how can I pass arguments to an event handler function?
我在这里查看 jQuery文档中“ click”事件的示例。 我可以如下重构两个匿名函数,它仍然可以工作:
$(document).ready(function(){
$("p").hover(hilite, remove_hilite);
});
function hilite()
{
$(this).addClass("hilite");
}
function remove_hilite()
{
$(this).removeClass("hilite");
}
但是,如果我要将参数传递给hilite
怎么办? 我的第一个猜测是我应该使用像这样的匿名函数。 但是,即使我不带参数使用它,这似乎也不起作用:
$("p").hover(
function()
{
hilite();
}
,
function()
{
remove_hilite();
}
);
我还尝试了如下重构,但这还是行不通的:
$(document).ready(function(){
$("p").hover(hilite2, remove_hilite);
});
function hilite2(){
return hilite();
}
正确的方法是什么? 我觉得我在概念上有很大的误解。 特别是,我不清楚在我的第一次重构中如何this
对象传递给hilite
函数。
您可以将悬停函数调用封装到另一个接受“ className”参数的函数中:
$.fn.hoverClass = function(className){
return this.hover(function(){
$(this).addClass(className);
}, function(){
$(this).removeClass(className);
});
}
然后,您可以通过以下方式简单地使用它:
$('p').hoverClass('hilite');
我认为您想要的是部分功能应用程序 。
function partial(func /*, 0..n args */) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(this, allArguments);
};
}
使用上述功能,您现在可以执行以下操作:
$(document).ready(function(){
var f = partial(hilite, "arg1", "arg2" /*etc...*/);
$("p").hover(f, remove_hilite);
});
为什么不能简单地在匿名函数中调用$(this).addClass()
方法?
$("p").hover(
function () {
$(this).addClass("hilight");
},
function () {
$(this).removeClass("hilight");
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.