簡體   English   中英

jQuery-從each()函數訪問所有元素

[英]jQuery - access all elements from a each() function

我有一個jQuery函數,可以掛在所有輸入元素上,例如:

$("input").blah();

如何從此函數中訪問此類型的所有元素? 不只是jQuery當前正在處理的那個。

該函數如下所示:

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

     this.each(function(){

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

       return this;
     });

 };

})(jQuery);

我想從所有這些元素中讀取一些屬性,然后根據這些屬性對正在處理的當前元素進行一些處理

(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回調。

聽起來您希望基於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);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM