jQuery插件返回this.each并将函数属性添加到每个对象? [英] jQuery Plugin Return this.each and add function property to each object?
问题描述
是否可以创建一个jQuery插件,该插件返回this.each用于多个匹配,从而允许我为每个循环中的每个对象添加一个函数属性?我希望稍后直接从对象中调用此函数。
Is it possible to create a jQuery plugin that returns this.each for multiple matches allowing me to add a function property to each object within the each loop? I want to call this function later directly off of the object.
例如,以下是我正在尝试执行的简化版本:
For example, here's a simplified version of what I'm trying to do:
(function ( $ ) {
$.fn.roflcopter = function( options ) {
return this.each(function() {
$(this).addClass('lol');
$(this).getMyValue = function(e){
return returnMyFilteredValue($(this));
}
});
function returnMyFilteredValue(elem){
return $(elem).val().replace("cat", "dog");
}
};
}( jQuery ));
然后我想在一个document.ready函数中调用它:
I then want to in a document.ready function call this:
$("input.coolStuff").roflcopter();
var value = $("input.coolStuff").first().getMyValue();
这可能吗?我收到一个错误,指出getMyValue不是一个函数。
Is this possible? I get an error stating that getMyValue is not a function.
推荐答案
次要变化:只需将getMyValue上 '这个',而不是$(本)和由
Minor change: just place getMyValue on 'this' and not on $(this) and access it by
$("input.coolStuff").first()[0].getMyValue()
这篇关于jQuery插件返回this.each并将函数属性添加到每个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!