javascript 如何在 .click() 函数中传递参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31939369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I pass arguments in .click() function?
提问by Amrinder Singh
I want to pass arguments to the click()
handler function in the following case:
我想click()
在以下情况下将参数传递给处理程序函数:
function edit_tab(val){
var prev_tab = $("#current_tab").html();
if (prev_tab == 1) {
$('.edit-basic-info').click(a); // here I want to pass some argument "a".
}
}
How can I pass the argument a in the above code? The way I am trying to do is not working.
如何在上面的代码中传递参数 a?我试图做的方式是行不通的。
回答by billyonecan
You can use trigger()'s
extraParameters
to pass additional parameters to your handler:
您可以使用trigger()'s
extraParameters
将其他参数传递给您的处理程序:
From the trigger()
documentation:
从trigger()
文档:
extraParameters Type: Array or PlainObject Additional parameters to pass along to the event handler.
extraParameters 类型:Array 或PlainObject 要传递给事件处理程序的附加参数。
Example (also from the documentation):
示例(也来自文档):
$( "#foo" ).on( "custom", function( event, param1, param2 ) {
alert( param1 + "\n" + param2 );
});
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );
回答by Madara's Ghost
Use a closure:
使用闭包:
function doSomething(myParam) {
return function(event) {
// Use both myParam and event here
};
}
And in your event handler:
在您的事件处理程序中:
$('#foo').on('click', doSomething('parameter')); // Works fine
The reason this works is that the call to doSomething('parameter')
returns a function, the inner function is not executed until the click handler calls it, and it can use all of the parameters passed to it from the outside.
这样做的原因是调用doSomething('parameter')
返回一个函数,内部函数在单击处理程序调用它之前不会执行,并且它可以使用从外部传递给它的所有参数。
回答by Sameer
<script>
function edit_tab(val){
var prev_tab=$("#current_tab").html();
if(prev_tab==1){
$('.edit-basic-info').bind('click', function () {
fndosomething(a)
//pass value in that function and use it
});
}
}
</script>
回答by Developer
bit more you can do like this
你还可以这样做
var message = 'check';
$('button').click({msg: message},functionFoo);
function functionFoo(e){
alert(e.data.msg);
}