manually calling click() on a button, can I pass any parameters?
I am manually c开发者_开发技巧alling .click() on a button on a page in my jquery/javascript code.
I need to pass a parameter to click that I can then read on the function that responds to the click event.
is this possible?
You need to invoke .trigger()
. You can pass over any amount of arguments there.
$('element').trigger('click', [arg1, arg2, ...]);
These extra parameters are then passed into the event handler:
$('element').bind('click', function(event, arg1, arg2, ...) {
});
Reference: .trigger()
<button id='test'>
var btn = $("button#test");
btn.attr("param", "my parameter");
btn.click();
No. Your onclick
event is separate from your click()
function. Normally, this would be possible through arguments[]
, but in this case you're going to have to use a variable.
What kind of argument do you want to pass? I get that these argument are static, since clicking on a button cannot give you any sort of computation.
When you catch the click, you can use this
, thus, use it to see what kind of arguments you want to pass
HTML:
<input type="button" id="foo" />
And your JS:
<script>
function iNeedParams(bar, baz) {
// Computation
}
$("id").click(function() {
var me = $(this);
// me contains the object
// me.attr("id") gives you its ID, then you can call
iNeedParams("hello", "world");
});
</script>
精彩评论