'$(this)' 和 'this' 有什么区别? [英] What's the difference between '$(this)' and 'this'?

查看:127
本文介绍了'$(this)' 和 'this' 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习本教程:jQuery 入门

I am currently working through this tutorial: Getting Started with jQuery

对于下面的两个例子:

$("#orderedlist").find("li").each(function (i) {
    $(this).append(" BAM! " + i);
});
$("#reset").click(function () {
    $("form").each(function () {
        this.reset();
    });
});

请注意,在第一个示例中,我们使用 $(this) 在每个 li 元素内附加一些文本.在第二个例子中,我们在重置表单时直接使用了this.

Notice in the first example, we use $(this) to append some text inside of each li element. In the second example we use this directly when resetting the form.

$(this) 似乎比 this 使用得更频繁.

$(this) seems to be used a lot more often than this.

我的猜测是在第一个示例中,$() 正在将每个 li 元素转换为理解 append() 的 jQuery 对象函数而在第二个示例中 reset() 可以直接在表单上调用.

My guess is in the first example, $() is converting each li element into a jQuery object which understands the append() function whereas in the second example reset() can be called directly on the form.

基本上我们需要 $() 用于特殊的 jQuery-only 函数.

Basically we need $() for special jQuery-only functions.

这是正确的吗?

推荐答案

是的,当您使用 jQuery 时,您只需要 $().如果您希望 jQuery 帮助做 DOM 事情,请记住这一点.

Yes you only need $() when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.

$(this)[0] === this

基本上每次你得到一组元素时,jQuery 都会把它变成一个 jQuery 对象.如果你知道你只有一个结果,它就会出现在第一个元素中.

Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.

$("#myDiv")[0] === document.getElementById("myDiv");

等等……

这篇关于'$(this)' 和 'this' 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆