我试图了解 jQuery
中 $(this)
和 this
之间的区别,并最终找到一种方法来获取$(this)
来自 this
的对象(this
是什么??):
var last_btn;
$("#element").click (function () {
if (last_btn != null && last_btn == this) {
// to unselect the current button
last_btn.removeClass ("selected"); // doesn't work because this is not $(this)
} else {
if (last_btn != null) last_btn.removeClass ("selected"); // to unselect another old button
last_btn = this;
$(this).addClass ("selected");
}
});
写在this post ,我需要使用 this
而不是 $(this)
对象,因为这是将 jQuery
对象分配给 var 而不会松散他的唯一方法实例。
我该怎么做?
最佳答案
在您显示的代码中,this
是对 ID element
被点击的纯 DOM 对象的引用。
$(this)
会将 DOM 对象扩展为 jQuery object ,这使得像 addClass
这样的所有 jQuery 优点都可用。
关于javascript - jQuery:$(this) 和 this 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4058937/