2009年2月26日 星期四

jQuery – this 和 $(this) 這兩個有什麼不一樣?

剛剛使用jQuery 一定對於this 和 $(this)有一點迷思。我第一次使用時也不是很情楚,所以我小小研究了一下發現:
$(this) 是用在jQuery,指的是「最近被選擇的物件」。
this是javascript,的「最近被選擇的物件」。
它們最大的不同是 $(this) 可以用jQuery的functions反之 this 不可以。所以當你沒有打算用jQuery的functions 時,它們兩個所代表的事情是一樣的。


例子:
不正確

$(".input").click(function() {
this.addClass("input_style");
});

正確

$(".input").click(function() {
this.addClass("input_style");
});