getElementById 和 jquery $('#smth') 之间的区别
有什么区别:
document.getElementById('theID')
经典 Javascript 代码和 jQuery 版本
$('#theID')
What's the difference between classic Javascript code:
document.getElementById('theID')
and the jQuery version:
$('#theID')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
document.getElementById
返回一个 DOM 对象。这是浏览器思考页面中元素的本机方式。它有多种方法和属性。这些使用起来可能有点笨拙。jQuery 对象(由
$
方法创建)是一个 DOM 元素或一组 DOM 元素的包装器。正常的属性和方法不可用;您可以选择不同的方法,使 DOM 操作过程更加直观。在选择中使用多个元素时,差异会更明显(例如使用类选择器
$('.someClass')
得到的结果,但 jQuery 选择的方法与它们指向同一件事,但思考和处理它的方式不同。最后一点,您可以使用 < 将 jQuery 选择转换为其本机 DOM 元素。一个href="http://api.jquery.com/get" rel="noreferrer">
get
方法(编辑:或替代的类似数组的语法)。与注意相同
,但是,您应该使用第一个,因为它具有更好的性能,仅当您需要它提供的额外功能时才使用 jQuery。
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). Sois exactly the same as
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.
那么在您的第二个项目中,您可能没有在顶部包含 jQuery 文件。
Well in your second project, you might not have included the jQuery files at the the top.
确保
在您的 中包含>
如果您未加载
jQuery
,则无法使用$
,因为 jQuery 是外部库,而不是 JavaScript 的一部分。Make sure to include
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
In your
<head>
If you don't load
jQuery
then you cannot use$
as jQuery is an external library and not part of JavaScript.不完全是:
如果页面上不存在具有该 id 的元素
$("#id") 将不起作用并且脚本将停止
document.getElementById("id") 将返回 null
Not quite :
If an element with that id is not existing on the page
$("#id") will not work and the script will stop
document.getElementById("id") will return null