jQuery中$('selector')和$('selector')[0]之间的区别 [英] Difference between $('selector') and $('selector')[0] in jquery

查看:46
本文介绍了jQuery中$('selector')和$('selector')[0]之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个< div class ="test" style ="width:200px"></div> ,请考虑以下内容:

Assuming i have a <div class="test" style="width:200px"></div>,Please consider the following:

var m = $('.test')[0];
var $md = $(m);
console.log($md.width()); //200

var o = $('.test');
console.log(o.width());  // 200


console.log(m);   // <div class="test" style="width:200px">
console.log($md);  // Object{ context: <div.test> ..... } 
console.log(o);   // Object{ length:1 , ..... }

基本上,我可以在 var $ md var o 上应用 width 方法,因此第一种方法和第二种方法之间的区别是什么如果输出是否相同?
我看到 md o 都是对象,但是在控制台输出中它们并不完全相同,它们有何不同?谢谢.

Basically i can apply the width method on either var $md or var o, so what's the difference between the 1st and 2nd way if the output is the same?
I see that both md and o are objects, but in the console output they not exactly the same, how do they differ? thanks.

推荐答案

在这里,您将获得第一个与元素匹配的选择器,它将返回纯js实例.

Here you get the first element matched selector, it returns plain js instance.

var m = $('.test')[0]; 

在这里,您再次将其包装在jQuery对象中.

Here you wrap it in a jQuery object again.

var $md = $(m);

因为 width()方法返回集合中第一个元素的宽度,所以两者之间没有区别方法,直到页面上有多个 .test 元素并且想要像这样更改它们:

Since width() method return width of the first element in set there is no difference between approach, until you've got a multiple .test elements on a page and want to change them like this:

 $('.test').width(100)

此代码会将页面上每个 .test 元素的宽度设置为100px.

This code will set the width of each .test element on a page to 100px.

但是,这只会继续更改集合中的第一个匹配元素:

But this continue to change only first matched element in a set:

 var el = $('.test')[0];
 $(el).width(100);


有一些基于您的代码的综合示例,我认为最好这样写:


There are synthetic examples based on your code, i think it's better to write this way:

$('.test').first().width(100);

$('.this:first').width(100);

这篇关于jQuery中$('selector')和$('selector')[0]之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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