我有一个jQuery函数,可以挂在所有输入元素上,例如:$("input").blah();
如何从此函数中访问此类型的所有元素?不只是jQuery当前正在处理的那个。
该函数如下所示:
(function($) {
$.fn.blah = function(){
this.each(function(){
// how can I access all elements of type "this" here?
return this;
});
};
})(jQuery);
我想从所有这些元素中读取一些属性,然后根据这些属性对正在处理的当前元素进行一些处理
最佳答案
听起来您希望基于type
属性过滤输入。
我不知道您最终想要完成什么,但是我想您可能不想在.each()
循环中完成它。
我会先过滤不同的类型,然后执行循环。
(function($) {
$.fn.blah = function(){
var text = this.filter('[type=text]');
var radio = this.filter('[type=radio]');
var checkbox = this.filter('[type=checkbox]');
text.each(function(){
// do something with all "text" inputs
return this;
});
};
})(jQuery);
另一种选择是只有一个循环,但根据
type
的值执行不同的操作。仅当您不需要整个集合时,这才起作用。(function($) {
$.fn.blah = function(){
this.each(function(){
if( this.type === "text" ) {
// do something with text inputs
} else if( this.type === "checkbox" ) {
// do something with checkboxes
}
// and so on
});
};
})(jQuery);