2012-11-22 32 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();' –

相关问题