是这样的:
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对象。
另一个区别是:getElementById返回第一个匹配项,而$('#…')返回一个匹配项的集合——是的,相同的ID可以在HTML文档中重复出现。
此外,getElementId从文档中调用,而$('#…')可以从选择器中调用。因此,在下面的代码中,document.getElementById('content')将返回整个主体,但$('form #content')[0]将返回表单内部。
<body id="content">
<h1>Header!</h1>
<form>
<div id="content"> My Form </div>
</form>
</body>
使用重复的id可能看起来很奇怪,但如果你使用像Wordpress这样的东西,模板或插件可能会使用与你在内容中使用的相同的id。jQuery的选择性可以帮助您解决这个问题。
不完全是! !
document.getElementById('contents'); //returns a HTML DOM Object
var contents = $('#contents'); //returns a jQuery Object
在jQuery中,获得与document相同的结果。getElementById,您可以访问jQuery对象并获得对象中的第一个元素(记住JavaScript对象的行为类似于关联数组)。
var contents = $('#contents')[0]; //returns a HTML DOM Object
接近,但不一样。它们得到相同的元素,但jQuery版本被包装在jQuery对象中。
等价的是这个
var contents = $('#contents').get(0);
或者这个
var contents = $('#contents')[0];
这将把元素从jQuery对象中拉出来。