getElementById与jquery $('#smth')之间的差异 [英] Diference between getElementById and jquery $('#smth')

查看:148
本文介绍了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]

但是,请注意,您应该使用冷杉t,因为它有更好的性能。如果你需要它提供的额外功能,只使用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天全站免登陆