如何使用带有 jQ​​uery 的 change() 方法的参数的函数?

2022-01-15 00:00:00 event-handling jquery javascript

我正在使用 jQuery 1.5 版.我在看 jQuery 的 change() 函数特别是在这一点:

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.

JavaScript 中的数据映射"到底是什么?如何使用以下测试函数作为事件处理程序?

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);};

我试过了:

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

并且警报报告 [object Object]

and the alert reports [object Object]

推荐答案

参见event.data.数据不会作为参数传递给处理程序,而是作为事件对象的属性:

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);
});

处理程序始终只接受一个参数,即 event 对象.这就是您的警报显示 "[object Object]" 的原因,您的函数正在打印事件对象.
如果你想使用带有自定义参数的函数,你必须将它们包装到另一个函数中:

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);
});

或者只是

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

<小时>

顺便说一句.选择器最好写成 $('#test').ID 是(应该)唯一的.无需在标签名称前添加.


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

相关文章