您的位置:首页 > Web前端 > JQuery

jquery $() 和document.getElementById() 区别

2011-11-16 15:29 337 查看
jQuery的$()和document.getElementById()的区别
2011-05-18 17:57

原文链接: http://codeclimber.net.nz/archive/2008/04/11/beware-the-.-in-jquery-elementid-document.getelementbyidelementid.aspx
$("element").get(0)=document.getElementById("element");

Lately I've been playing a bit with
jQuery, one of the raising javascript frameworks and I found out something I was not expecting to find.

But let's step back a bit: in jQuery the dollar sign function $ is a shortcut for themain function of the framework which is used to select html elements
in the page. This$ method accepts a css-like selector as argument, so if you want to select a specific element by its id you have to use the hash:$("#myElementId") returns a reference to the DOM element boosted by jQuery.
We can say it's a shortcut to the usual way of getting a DOM elementdocument.getElementById("myElementId").

With this idea in mind, thinking that jQuery added its goodness to the standard DOM Element via extension methods, and after reading on the docs thatwhen called with the id selector the jQuery method
returned a DOM Element, I was expecting to get a reference to the real DOM element. So I passed it to an ASP.NET Javascript function and it complained that the DOM element didn't have a style property. Where was I wrong?

It took me a while to understand why I was wrong: the $ method gives a jQuery object that isalways an array of Elements, even
if the docs say otherwise.



So to the get the real DOM element you have to use $("#myElementId")[0] or the more friendly$("#myElementId").get(0)



So, just to wrap up, $("#elementId") != document.getElementById("elementId"). And comparing to the ASP.NET Ajax Library, it is also different from the$get("elementId")
which is exactly the same as doing the getElementById the old way.

It took me a whole afternoon to understand this... I hope this post will save you 4 hours of your time as well.

上一篇>> google
marker image 下一篇>> Google
Maps 两点或者多点间路径
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: