2011-01-30 71 views
0

我有大干快上像所有的输入元素勾住了jQuery函数访问的所有元素:jQuery的从每个()函数

$("input").blah();

我如何可以访问此类型的所有元素,从这个函数中?不仅仅是当前由jQuery处理的那个。

函数看起来象:

(function($) { 
    $.fn.blah = function(){ 

    this.each(function(){ 

     // how can I access all elements of type "this" here? 

     return this; 
    }); 

}; 

})(jQuery); 

我想读的所有这些元素的一些属性,然后做一些东西多数民众赞成当前正在处理的元素,根据这些属性

+0

你如何定义“这种类型”?你的意思是由输入上的`type`属性字面意思吗? – user113716 2011-01-30 20:04:28

+0

是的帕特里克dw。 – Alex 2011-01-30 20:06:37

+0

解决方案取决于您最终做了什么,但如果您需要将它们作为一个组进行操作,则应该将它们过滤为组。 – user113716 2011-01-30 20:14:15

回答

2

这听起来像你希望筛选基础上,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); 
6
(function($) { 
    $.fn.blah = function(){ 

    var that = this; 
    this.each(function(index, element){ 

     // this here means the element in that[i] 
     // that here means the original jQuery object. 

     return this; 
    }); 

}; 

})(jQuery); 

您可以将this保存在一个变量中,然后访问.each回调。

1

$('input').bind("whatever", function() { 
$('input [type="' + $(this).attr('type') + '"]).each(function() { 
    //...whatever code here 
    }); 
});