一些jQuery使用技巧(借)

1.像数组一样使用jQuery对象 

运行一个选择器得到的结果是一个jQuery对象。但是,通过jQuery可以使结果看起来更像一个数组,你可以定义索引元素和长度。 

  1. var buttons = $('#navigation a.button'); //Selecting all the navigation b //Selecting all the navigation buttons  
  2. // We can loop though the collection:  
  3. for(var i=0;i<buttons.length;i++){  
  4. console.log(buttons[i]); // A DOM element, not a jQuery object  
  5. }  

2.检查一个元素是否存在 

确定一个元素集合是否存在或是否包含元素的唯一方法是检查元素的长度。 

  1. If (buttons.length){ // True only if buttons contains elements  
  2. // Do something }  

3.把你的代码变成jQuery插件 

  1. function($){  
  2. $.fn.yourPluginName = function(){  
  3. // Your code goes here  
  4. return this;  
  5. };  
  6. })(jQuery);  

4.本地存储

 Local storage是一个用于在客户端上存储信息的API。使用时,你只需将你的数据作为localStorage全局对象的一个属性: 

localStorage.someData = "This data is going to persist across page refreshes and browser restarts";  

旧的浏览器不支持该API,不过有各种jQuery插件可以作为替代方案。这些插件在localStorage不可用时提供了其他存储方案。下面是一个例子: 

  1. // Check if "key" exists in the storage.  
  2. var value = $.jStorage.get("key");  
  3. if(!value){  
  4. // if not - load the data from the server  
  5. value = load_data_from_server();  
  6. // and save it  
  7. $.jStorage.set("key",value);  

 

 

 

 

posted @ 2013-04-12 15:04  白白的技术千千的生活  阅读(212)  评论(0编辑  收藏  举报