How do I bind an event handler to the "change" JavaScript event, or trigger that event on an element?
I do not understand how to get change event to call a function.
$(function () {
function foo() {
开发者_Go百科 alert("ok");
}
//works
$('#myElement').change(function() {
alert("ok");
});
//does not work
$('#myElement').change(foo);
//does not work
$('#myElement').change(foo());
}
All of the following examples should work, if not then you are doing something wrong.
$(function() {
function foo(e) {
alert("ok");
}
$('#myElement').change(function(e) {
alert("ok");
});
$('#myElement').change(foo);
//trigger the event like so:
$('#myElement').change();
});
$('#myElement').change(function() {
foo();
});
versions 1 and 2 work for me on FF3.6 and IE7. version 3 executes right away because of the presence of the parenthesis. Can you give the browser on which version 2 is not working.
to bind a function to the change event :
$('#id').bind('change',function(){/*code here*/});
and to trigger the event :
$('#id').trigger('change');
This should work:
$('#myElement').change(foo);
In your code example you are missing one closing bracket.
精彩评论