How to use a function that takes arguments with jQuery's change() method?

强颜欢笑 提交于 2019-11-27 20:23:21

See event.data. The data is not passed as argument to handler, but as property of the event object:

$("select#test").change({msg: "ok"},  function(event) {
    alert(event.data.msg);
});

The handler always only accepts one argument, which is the event object. This is the reason why your alert shows "[object Object]", your function is printing the event object.
If you want to use functions with custom arguments, you have to wrap them into another function:

$("select#test").change({msg: "ok"},  function(event) {
    myHandler(event.data.msg);
});

or just

$("select#test").change(function(event) {
    myHandler("ok");
});

Btw. the selector is better written as $('#test'). IDs are (should be) unique. There is no need to prepend the tag name.

What exactly is a "map of data" in Javascript?

Basically just an object, e.g.:

var data = {
    foo: "I'm foo",
    bar: "I'm bar"
};

All JavaScript objects are essentially maps (aka "dictionaries" aka "associative arrays").

How can I use the following test function as an event handler?

By wrapping it in another function:

$("select#test").change(function() {
    myHandler($(this).val());
});

That calls myHandler with the value of the select box whenever it changes.

If you want to use the eventData part, add an object prior to the handler:

$("select#test").change({
    foo: "I'm foo"
}, function(event) {
    myHandler(event.data.foo, $(this).val());
});

That calls myHandler with the "I'm foo" as the first argument, then the value of the select box, whenever it changes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!