如何在jquery事件处理程序中传递对象方法?

我有一堆调用特定jQuery插件的处理程序。 我想重构代码并创建一个对象,其属性和方法可以传递给一个包装器,然后调用该插件。

问题:我在模仿以下声明时遇到困难:

$("li", opts.tgt).live("click", function () { GetContact(this); }); 

有人对如何进行有一些建议吗? TIA。

 function InitAutoCompleteTest() { // Init custom autocomplete search var opts = { tgt: "#lstSug", crit: "#selCrit", prfxID: "sg_", urlSrv: gSvcUrl + "SrchForContact", fnTest: function (str) { alert(str) }, fnGetData: function (el) { GetContact(el) } } $("input", "#divSrchContact").bind({ "keypress": function (e) { // Block CR (keypress fires before keyup.) if (e.keyCode == 13) { e.preventDefault(); }; }, "keyup": function (e) { // Add suggestion list matching search pattern. opts.el = this; $(this).msautocomplete(opts); e.preventDefault(); }, "dblclick": function (e) { // Clear search pattern. $(this).val(""); } }); opts.fnTest("Test"); // Works. Substituting the object method as shown works. // Emulation attempts of below statement with object method fail: // $("li", opts.tgt).live("click", function () { GetContact(this); }); $("li", opts.tgt).live({ "click": opts.fnGetData(this) }); // Hangs. $("li", opts.tgt).live({ "click": opts.fnGetData }); // Calls up GetContact(el) but el.id in GetContact(el) is undefined } function GetContact(el) { // Fired by clicking on #lstSug li. Extract from selected li and call web srv. if (!el) { return }; var contID = el.id, info = $(el).text(); ... return false; } 

编辑

感谢您的反馈。 我终于使用了Thiefmaster提出的变体。 我只是想知道为什么这个方法必须嵌入匿名fn中,因为“opts.fnTest(”Test“);” 可以说,开箱即用。

  $("li", opts.tgt).live({ "click": function () { opts.fnGetData(this); } }); 

只需将它们包装在匿名函数中:

 function() { opts.fnGetData(); } 

另一个需要现代JS引擎的选项是使用.bind()

 opts.fnGetData.bind(opts) 

完整示例:

 $("li", opts.tgt).live({ "click": opts.fnGetData.bind(opts) }); $("li", opts.tgt).live({ "click": function() { opts.fnGetData(); }}); 

在回调中,您可以使用this来访问该对象。


如果要将元素作为参数传递,可以这样做:

 $("li", opts.tgt).live({ "click": function() { opts.fnGetData(this); }}); 

从文档

 .live( events, data, handler(eventObject) ) 

events包含JavaScript事件类型的字符串,例如“click”或“keydown”。 从jQuery 1.4开始,字符串可以包含多个空格分隔的事件类型或自定义事件名称。

data将传递给事件处理程序的数据映射。

handler(eventObject)触发事件时要执行的函数。

例:

 $('#id').live('click', {"myValue":"someValue"}, function(evt){ console.log(evt.data["myValue"]); // someValue });​ 

JQuery直播