2012-11-22 47 views
0

請幫助我將我的功能添加到所有div。我想用'each',但不知道如何。我試圖使用$('div')。test()函數時,我只需要2個警告消息,但我只成爲第一個div。它仍然有效。如何使用我自己創建的多個項目的jQuery函數?

<html> 
    <head> 

     <style type="text/css"> 
      div { 
       width:100px; 
       height:100px; 
       background: yellow; 
       float: left; 
       margin: 20px; 
      } 
     </style> 

     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 

    </head> 

    <body> 

     <div id="a"></div> 
     <div id="b"></div> 

     <script type="text/javascript"> 

      (function($){ 

       $.fn.test = function() { 

        alert(this.attr('id')); 

       }; 

      })(jQuery); 

      //work 
      $('#a').test(); 

      // not work 
      //$('div').test(); 

     </script> 
    </body> 
</html> 

Thanx!

+0

等都不是幫助論壇,請嘗試以不太特定的方式重新提出您的問題,更有可能幫助其他用戶解決同樣的問題。 – OneChillDude

+3

@ bwheeler96問題有什麼問題?似乎對我很清楚 – charlietfl

回答

3

更改您的警戒線到:

return this.each(function(){ alert(this.id); }); 

請參閱該文檔的jQuery each

這是JSFiddle

+0

但我需要使用'this'相同'this.hide()'jQuery的功能' – iBoozyVoozy

+0

@iBoozyVoozy你可以像'$(this)'一樣包裝'this',然後調用像' $(this).hide();'或'$(this).show();'。但是,強烈建議您僅出於效率原因而僅爲每個函數範圍編寫'$(this)'。您可以將結果緩存在名爲'$ this'的變量中,以避免多次執行此操作。 – Paulpro

+0

所以'var $ this = $(this);'然後你可以做一些像'$ this.show();'和'$ this.hide();' – Paulpro

1

你的第一個例子...

$('#a').test(); 

...工程,因爲只有一個以 「a」 的ID元素。然而,你的第二個例子......

$("div").test(); 

...不,因爲它是選擇在頁面上的div的所有

你需要這樣的支持兩種可能性:

(function($){ 
    $.fn.test = function() { 
     // this is now all selected elements. 
     // Loop through each selected element. 
     $(this).each(function() { 
      // this is now the element being looped. 
      alert($(this).attr('id')); 
     }); 
    }; 
})(jQuery); 

的jsfiddle:http://jsfiddle.net/2Ejux/

+0

我的歉意。我已經做了更正。 – Selosindis

+0

oooooooomg)thanx you。它很棒! – iBoozyVoozy

2

http://jsfiddle.net/bu952/1/

(function($){ 

    $.fn.test = function() { 

    return this.each(function() { 
     alert(this.id); 
    }); 

    }; 
})(jQuery); 


$('div').test(); 
+0

omg)thanx you !!! – iBoozyVoozy

+0

對不起,但我需要使用jQuery的功能。例如:'this.hide()' – iBoozyVoozy

+0

@iBoozyVoozy隱藏什麼?我真的不明白。你想在這裏完成什麼?隱藏兩個或特定的一個?而不是alert(this.id);'use:'$(this).hide();' –

相關問題