How to use a function that takes arguments with jQuery#39;s change() method?(如何使用带有 jQuery 的 change() 方法的参数的函数?)
问题描述
我正在使用 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.
这篇关于如何使用带有 jQuery 的 change() 方法的参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用带有 jQuery 的 change() 方法的参数的函数?


基础教程推荐
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01