jquery $(this) this
jQuery 中的 $(this) 与 this 的区别
在 jQuery 中,$(this) 和 this 是两个常见但容易混淆的概念。以下是它们的核心区别和用法:
$(this)
- 将原生 DOM 元素包装成 jQuery 对象,可以使用 jQuery 提供的方法。
- 适用于需要调用 jQuery 方法的场景,例如操作 DOM、绑定事件等。
- 示例:
$('button').click(function() { $(this).hide(); // 使用 jQuery 的 hide() 方法 });
this
- 指向当前 DOM 元素的原生 JavaScript 对象。
- 适用于需要直接访问 DOM 属性或调用原生方法的场景。
- 示例:
$('button').click(function() { console.log(this.textContent); // 直接访问原生属性 });
如何选择使用
需要调用 jQuery 方法时使用 $(this),例如:
$(this).addClass('active');
需要访问原生属性或方法时使用 this,例如:
this.setAttribute('data-id', '123');
相互转换
可以将 this 转换为 $(this):
var jqueryObj = $(this);
也可以将 $(this) 转换回原生 DOM 元素:
var domElement = $(this)[0];
// 或
var domElement = $(this).get(0);
常见应用场景
事件处理程序中经常同时使用两者:

$('a').click(function() {
// 使用 this 获取原生属性
var href = this.href;
// 使用 $(this) 调用 jQuery 方法
$(this).css('color', 'red');
});






