开发者

Jquery Code help

I wrote a jquery script:

$(document).ready(function(){  
$("#category").click(function(){  
    $("#category_menu").slideToggle(1000);  
    });  
  $("body").click(function(){  
    $("#category_menu").hide();  
  });  
});

My Question is, is there any way to reduce the size to look more 开发者_JAVA技巧"professional" ?


the only way i can see to reduce it is to do:

$(function(){  
   $("#category").click(function(){  
       $("#category_menu").slideToggle(1000);  
    });  
    $("body").click(function(){  
       $("#category_menu").hide();  
    });  
});


First you should use the document.ready shortcut and alias jQuery to $ to allow cross-library support, and you can store the #category_menu lookup to expedite the functions. But really your code is fine as-is.

jQuery(function($){
  var $cm = $('#category_menu');
  $('#category').click(function(){
    $cm.slideToggle(1000);
  });
  $('body').click(function(){
    $cm.hide();
  });
});


Anything clicked on that's not #category will hide #category_menu. You also don't need document ready function if you place your jQuery just before </body>

$("#category, html").click(function(e) {
    e.stopPropagation();
    this.id == 'category' ? $("#category_menu").slideToggle(1000) : $("#category_menu").hide();
});

Check working example at http://jsfiddle.net/QDfnh/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜