10 个很棒的 jQuery 代码片段

图片预加载

  (function($) {   var cache = [];   // Arguments are image paths relative to the current page.   $.preLoadImages = function() {     var args_len = arguments.length;     for (var i = args_len; i--;) {       var cacheImage = document.createElement('img');       cacheImage.src = arguments[i];       cache.push(cacheImage);     }   }  jQuery.preLoadImages("image1.gif", "/path/to/image2.png"); 

 在新窗口打开链接 (target="blank")

$('a[@rel$='external']').click(function(){      this.target = "_blank"; });  /*    Usage:    <a href="http://www.catswhocode.com" rel="external">catswhocode.com</a> */

当支持 JavaScript 时为 body 增加 class

  /* 该代码只有1行,但是最简单的用来检测浏览器是否支持 JavaScript 的方法,如果支持 JavaScript 就在 body 元素增加一个 hasJS 的 class */ $('body').addClass('hasJS');

平滑滚动页面到某个锚点

  $(document).ready(function() {  $("a.topLink").click(function() {   $("html, body").animate({    scrollTop: $($(this).attr("href")).offset().top + "px"   }, {    duration: 500,    easing: "swing"   });   return false;  }); });

鼠标滑动时的渐入和渐出

  $(document).ready(function(){     $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads      $(".thumbs img").hover(function(){         $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover     },function(){         $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout     }); });

 制作等高的列

  var max_height = 0; $("div.col").each(function(){     if ($(this).height() > max_height) { max_height = $(this).height(); } }); $("div.col").height(max_height);

在一些老的浏览器上启用 HTML5 的支持

  (function(){     if(!/*@cc_on!@*/0)         return;     var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(','),i=e.length;while(i--){document.createElement(e[i])} })()  //然后在head中引入该js <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]-->

 测试浏览器是否支持某些 CSS3 属性

  var supports = (function() {    var div = document.createElement('div'),       vendors = 'Khtml Ms O Moz Webkit'.split(' '),       len = vendors.length;     return function(prop) {       if ( prop in div.style ) return true;        prop = prop.replace(/^[a-z]/, function(val) {          return val.toUpperCase();       });        while(len--) {          if ( vendors[len] + prop in div.style ) {             // browser supports box-shadow. Do what you need.             // Or use a bang (!) to test if the browser doesn't.             return true;          }       }       return false;    }; })();  if ( supports('textShadow') ) {    document.documentElement.className += ' textShadow';

 获取 URL 中传递的参数

 $.urlParam = function(name){  var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);  if (!results) { return 0; }  return results[1] || 0; }

禁用表单的回车键提交

  $("#form").keypress(function(e) {   if (e.which == 13) {     return false;   } });

Bash快捷键

编辑命令

  • Ctrl + a :移到命令行首
  • Ctrl + e :移到命令行尾
  • Ctrl + f :按字符前移(右向)
  • Ctrl + b :按字符后移(左向)
  • Alt + f :按单词前移(右向)
  • Alt + b :按单词后移(左向)
  • Ctrl + xx:在命令行首和光标之间移动
  • Ctrl + u :从光标处删除至命令行首
  • Ctrl + k :从光标处删除至命令行尾
  • Ctrl + w :从光标处删除至字首
  • Alt + d :从光标处删除至字尾
  • Ctrl + d :删除光标处的字符
  • Ctrl + h :删除光标前的字符
  • Ctrl + y :粘贴至光标后
  • Alt + c :从光标处更改为首字母大写的单词
  • Alt + u :从光标处更改为全部大写的单词
  • Alt + l :从光标处更改为全部小写的单词
  • Ctrl + t :交换光标处和之前的字符
  • Alt + t :交换光标处和之前的单词
  • Alt + Backspace:与 Ctrl + w 相同类似,分隔符有些差别 [感谢 rezilla 指正]

重新执行命令

  • Ctrl + r:逆向搜索命令历史
  • Ctrl + g:从历史搜索模式退出
  • Ctrl + p:历史中的上一条命令
  • Ctrl + n:历史中的下一条命令
  • Alt + .:使用上一条命令的最后一个参数

控制命令

  • Ctrl + l:清屏
  • Ctrl + o:执行当前命令,并选择上一条命令
  • Ctrl + s:阻止屏幕输出
  • Ctrl + q:允许屏幕输出
  • Ctrl + c:终止命令
  • Ctrl + z:挂起命令

Bang (!) 命令

  • !!:执行上一条命令
  • !blah:执行最近的以 blah 开头的命令,如 !ls
  • !blah:p:仅打印输出,而不执行
  • !$:上一条命令的最后一个参数,与 Alt + . 相同
  • !$:p:打印输出 !$ 的内容
  • !*:上一条命令的所有参数
  • !*:p:打印输出 !* 的内容
  • ^blah:删除上一条命令中的 blah
  • ^blah^foo:将上一条命令中的 blah 替换为 foo
  • ^blah^foo^:将上一条命令中所有的 blah 都替换为 foo

友情提示:

  1. 以上介绍的大多数 Bash 快捷键仅当在 emacs 编辑模式时有效,若你将 Bash 配置为 vi 编辑模式,那将遵循 vi 的按键绑定。Bash 默认为 emacs 编辑模式。如果你的 Bash 不在 emacs 编辑模式,可通过 set -o emacs 设置。
  2. ^S、^Q、^C、^Z 是由终端设备处理的,可用 stty 命令设置。

java: Can == be used on enum?

Can == be used on enum?

Yes: enums have tight instance controls that allows you to use == to compare instances. Here's the guarantee provided by the language specification:

JLS 8.9 Enums

An enum type has no instances other than those defined by its enum constants.

It is a compile-time error to attempt to explicitly instantiate an enum type. The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.

Because there is only one instance of each enum constant, it is permissible to use the ==operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant. (The equals method in Enumis a final method that merely invokes super.equals on its argument and returns the result, thus performing an identity comparison.)

This guarantee is strong enough that Josh Bloch recommends, that if you insist on using the singleton pattern, the best way to implement it is to use a single-element enum (see: Effective Java 2nd Edition, Item 3: Enforce the singleton property with a private constructor or an enum type; also Thread safety in Singleton)


What are the differences between == and equals?

As a reminder, it needs to be said that generally, == is NOT a viable alternative to equals. When it is, however (such as with enum), there are two important differences to consider:

== never throws NullPointerException

  enum Color { BLACK, WHITE };

Color nothing = null;
if (nothing == Color.BLACK);      // runs fine
if (nothing.equals(Color.BLACK)); // throws NullPointerException

== is subject to type compatibility check at compile time

  enum Color { BLACK, WHITE };
enum Chiral { LEFT, RIGHT };

if (Color.BLACK.equals(Chiral.LEFT)); // compiles fine
if (Color.BLACK == Chiral.LEFT);      // DOESN'T COMPILE!!! Incompatible types!

Should == be used when applicable?

Bloch specifically mentions that immutable classes that have proper control over their instances can guarantee to their clients that == is usable. enum is specifically mentioned to exemplify.

Item 1: Consider static factory methods instead of constructors

[...] it allows an immutable class to make the guarantee that no two equal instances exist:a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the ==operator instead of the equals(Object) method, which may result in improved performance. Enum types provide this guarantee.

To summarize, the arguments for using == on enum are:

  • It works.
  • It's faster.
  • It's safer at run-time.
  • It's safer at compile-time.