問題描述
我正在使用 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.
這篇關于如何使用帶有 jQ??uery 的 change() 方法的參數的函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!