Any difference between a $ wrap function and getElementById?
I mean a wrap function like this:
function $(id) { return document开发者_JAVA技巧.getElementById(id); }
but in some code like this:
oDiv1 = $("postInfoDiv");
oDiv2 = document.getElementById("postInfoDiv");
alert(oDiv1 == oDiv2); // return false
alert(oDiv1.style); // error
alert(oDiv2.style); // correct
alert(document.getElementById("postInfoDiv").style); // correct
I got strange results as the comments imply.
I thought the first alert should return the true since they are the same dom object. I thought the second alert should alert something like "object" or "CSS StyleDeclaration" but not "defined".So what are the problems? Have you ever met this kind of problems?
thanks.
Your $
function is probably being overridden, potentially by a framework.
You should try doing alert( oDiv1.nodeType )
to see if it's a DOM element. alert( oDiv1.length )
to see if it's an empty array because you may be using jQuery on the same page which overrides your $
function.
oDiv1
may be an array-like object containing that item if jQuery is included. oDiv2
is an actual DOM reference. You probably need to compare oDiv1[0]
to oDiv1
, in which you reference the first element in the array which points to the actual dom element to make a fair comparison.
function $(id){return document.getElementById(id)}
$('content') == document.getElementById('content')
true
The custom $
function will work perfectly but if you're using a framework function it will return that array-like object instead of the DOM element.
You can also rename your function to something like function getID
which would be unique and not conflict with framework $
s.
My main concern with this is that it will confuse the heck out of someone the first time they read your code, especially if they are used to coding with a JavaScript framework such as jQuery.
For this reason alone I recommend you do not use this particular syntax for your wrap function.
BTW note that even when jQuery is not loaded, Firebug provides its own $ function, which may participate to confusion.
精彩评论