是这样的:
var contents = document.getElementById('contents');
和这个一样:
var contents = $('#contents');
jQuery加载?
是这样的:
var contents = document.getElementById('contents');
和这个一样:
var contents = $('#contents');
jQuery加载?
当前回答
Just like most people have said, the main difference is the fact that it is wrapped in a jQuery object with the jQuery call vs the raw DOM object using straight JavaScript. The jQuery object will be able to do other jQuery functions with it of course but, if you just need to do simple DOM manipulation like basic styling or basic event handling, the straight JavaScript method is always a tad bit faster than jQuery since you don't have to load in an external library of code built on JavaScript. It saves an extra step.
其他回答
Just like most people have said, the main difference is the fact that it is wrapped in a jQuery object with the jQuery call vs the raw DOM object using straight JavaScript. The jQuery object will be able to do other jQuery functions with it of course but, if you just need to do simple DOM manipulation like basic styling or basic event handling, the straight JavaScript method is always a tad bit faster than jQuery since you don't have to load in an external library of code built on JavaScript. It saves an extra step.
No.
调用document.getElementById('id')将返回一个原始DOM对象。
调用$('#id')将返回一个jQuery对象,该对象包装DOM对象并提供jQuery方法。
因此,只能在$()调用中调用css()或animate()等jQuery方法。
你也可以写$(document.getElementById('id')),它将返回一个jQuery对象,等价于$('#id')。
你可以通过编写$('#id')[0]从jQuery对象中获得底层DOM对象。
以上所有答案都是正确的。如果你想看到它的运行,不要忘记你在浏览器中有控制台,在那里你可以清楚地看到实际的结果:
我有一个HTML:
<div id="contents"></div>
转到控制台(cntrl+shift+c),使用这些命令可以清楚地看到结果
document.getElementById('contents')
>>> div#contents
$('#contents')
>>> [div#contents,
context: document,
selector: "#contents",
jquery: "1.10.1",
constructor: function,
init: function …]
正如我们所看到的,在第一种情况下,我们得到了标签本身(也就是说,严格地说,一个HTMLDivElement对象)。在后者中,我们实际上没有一个普通对象,而是一个对象数组。正如上面其他答案所提到的,你可以使用以下命令:
$('#contents')[0]
>>> div#contents
jQuery是基于JavaScript构建的。这意味着它只是javascript。
document.getElementById ()
getelementbyid()方法返回具有指定值的ID属性的元素,如果不存在具有指定ID的元素则返回null。一个ID在一个页面中应该是唯一的。
Jquery(美元)
以id选择器作为参数调用jQuery()或$()将返回一个包含0个或1个DOM元素的集合的jQuery对象。每个id值在文档中只能使用一次。如果多个元素被分配了相同的ID,使用该ID的查询将只选择DOM中第一个匹配的元素。
var contents = document.getElementById('contents');
Var contents = $('#contents');
代码片段是不一样的。第一个返回一个Element对象(source)。 第二个是jQuery等效函数,返回一个包含0个或1个DOM元素的集合的jQuery对象。(jQuery文档)。jQuery内部使用document.getElementById()来提高效率。
在这两种情况下,如果找到多个元素,则只返回第一个元素。
当检查github项目的jQuery时,我发现下面的行片段似乎正在使用文档。getElementById代码(https://github.com/jquery/jquery/blob/master/src/core/init.js第68行起)
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );