使用jQuery data()方法存储函数

jQuery .data()文档说明如下:

The .data() method allows us to attach data of any type to DOM element 

我假设“任何类型”也指function。 假设我有一个id为foo的div:

 
Foo!

我想在其中存储一个名为say的函数。 根据文档,我将以这种方式存储函数:

 $("#foo").data("say", function(message){ alert("Foo says "+message); }); 

我的问题是,当我希望这样做时,如何使用参数调用该函数。

$("#foo").data("say"); 应该返回函数,但是如何将参数传递给它?

谢谢!

 var myFunction = $("#foo").data("say"); myFunction(someParameter); 

data存储函数的更好的替代方法是使用自定义事件。 这可以通过ontrigger轻松完成:

 $('#foo').on('say', function(e, arg){ alert('Foo says ' + arg); }); $('#foo').trigger('say', 'hello'); 

示例: http : //jsfiddle.net/tW66j/

注意:在早期版本的jQuery(直到1.7)中,使用.bind而不是.on

这是一种更优雅的方法来调用该方法。

 // store the method with data $('#foo').data('bar',function(){console.log("Givin it the business!")}); // Simple execution (this will not keep the method in scope) $('#foo').data('bar')(); // scoped method execution with call([scope,arguments[]]), takes arguments with comma separation $('#foo').data('bar').call($('#foo').first()[0],'arguemnts','for','method'); // scoped method execution with apply(scope[,argument[]]), takes an array of arguments $('#foo').data('bar').apply($('#foo').first()[0],['arguemnts','for','method']); 

申请方法: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply

调用方法: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call