getElementById和jquery $('#smth')之间的区别 [英] Difference between getElementById and jquery $('#smth')

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

问题描述

经典Javascript代码有什么区别:

  document.getElementById('theID')

和jQuery版本:

  $('#theID')


解决方案

document.getElementById 返回DOM对象。这是浏览器对页面元素的固有思考方式。它具有各种方法和属性。这些可能会有点笨拙。



jQuery对象(由 $ 方法创建)是一个包装器围绕一个DOM元素或一组DOM元素。常规属性和方法不可用;您可以选择不同的方法,这些方法可以使DOM操作的过程更加直观。



在选择中包含多个元素时,区别更加明显(因为您会得到例如,使用类选择器 $('。someClass'),但是jQuery选择上的方法与本机DOM元素上的方法不同,它们指向相同的对象事情,但是它们是不同的思考方式和处理方式。






最后,您可以转换使用 get 将jQuery选择放入其本机DOM元素中方法(编辑:或其他类似数组的语法)。因此

  document.getElementById('theID') 



<$ p $完全相同p> $('#theID')。get(0)//或$('#theId')[0]

但是请注意,您应该使用第一个,因为它具有muc更好的表现。仅在需要jQuery提供的额外功能时使用jQuery。


What's the difference between classic Javascript code:

document.getElementById('theID')

and the jQuery version:

$('#theID')

解决方案

document.getElementById returns a DOM object. This is the browser's native way of thinking about an element in the page. It has various methods and properties. These can be a little clunky to use.

The jQuery object (created by the $ method) is a wrapper around a DOM element or a set of DOM elements. The normal properties and methods are not available; you get a selection of different methods that make the process of DOM manipulation more intuitive.

The difference is more clear to see with multiple elements in the selection (as you would get with a class selector $('.someClass') for instance, but the methods on a jQuery selection are different to the ones on a native DOM element. They point to the same thing, but they are different ways of thinking about it and dealing with it.


As a final note, you can convert a jQuery selection into its native DOM element(s) with the get method (edit: or the alternative array-like syntax). So

document.getElementById('theID')

is exactly the same as

$('#theID').get(0) // or $('#theId')[0]

Note, however, that you should use the first, as it has much better performance. Only use jQuery if you need the extra functionality it provides.

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

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