Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

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

I'm using jQuery version 1.5. I am looking at jQuery's change() function and specifically at this bit:

.change( [ eventData ], handler(eventObject) )
eventData: A map of data that will be passed to the event handler.
handler(eventObject): A function to execute each time the event is triggered.

What exactly is a "map of data" in JavaScript? How can I use the following test function as an event handler?

var myHandler = function(msg){alert(msg);};

I've tried this:

$("select#test").change(["ok"], myHandler);

and the alert reports [object Object]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...