如何将参数传递给事件处理程序? [英] How do I pass arguments to an event handler?
问题描述
我有一个函数对象,我想在使用jquery单击时将参数传递给它,但是它不起作用.
I have a function object to which I want to pass an argument on click using jquery, but it's not working.
<script>
var item=232;
$(function(){
$('div').click(fn_clik('Mike'))
})
var fn_clik = function(name){
alert('Name is:' + name + ' item is:' + item)
}
</script>
我不理解其背后的概念.谁能解释我要去哪里错了?
I don't understand the concept behind it. Can anyone please explain where am I going wrong?
推荐答案
让您正在调用的函数在闭包中返回一个带有由参数传递的名称的函数:
Have the function you are calling return a function with the name, passed by argument, in a closure:
$('div').click( fn_clik('Mike') );
var fn_clik = function(name){
return function() {
alert('Name is:' + name + ' item is:' + item);
}
}
或者您传递了一个匿名函数,将带有正确参数的原始函数包装起来:
Or have an anonymous function you pass wrap the original function called with the correct parameter:
$('div').click(function () {
fn_clik('Mike')
});
快速注释一下,在您的原始代码中,您正在调用函数"fn_clik",而不是将其作为对象传递.因此,您的代码评估为:
A quick note, in your original code, you were calling the function 'fn_clik' instead of passing it as an object. So your code was evaluating to:
$('div').click( undefined );
这是因为原始的"fn_clik"没有返回值;
This is because your original 'fn_clik' has no return value;
这篇关于如何将参数传递给事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!