javascript - jQuery:$(this) 和 this 之间的区别

标签 javascript jquery

我试图了解 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/

相关文章:

jQuery 的 .removeClass() 不会在移动设备上更新 DOM 中的 CSS

Jquery 隐藏从第 n 开始的元素。指数

javascript - Jasmine Node 要求 *

javascript - 这个操作是什么意思? {| ... |} 和 +attrName

javascript - "No locale data has been provided"不管传入什么

javascript - IFrame 和 Flash 广告 Z-Index 问题

javascript - 如何在不使用 {{#each}} 或 {{#if}} 的情况下从 Handlebars.js 中的 .json 文件获取数据?

javascript - 单击后如何使徽章通知在所有网页上消失

javascript - 获取具有相同类的多个输入字段的值并添加到javascript对象中

javascript - 与流沙的冲突