I'm one day into learning JQuery and have a question about the octothorpe syntax.
I am aware that the # can be used to specify the ID of an object.
Example:
HTML Object
<div id="myDiv">...</div>
JQuery Statement using #
...
$("#myDiv").hide();
...
However, I noticed that I can accomplish the same thing without using the #.
JQuery statement without using #
...
$(myDiv).hide();
...
I prefer the syntax that does not involve the quotes and octothorpe, but I am 开发者_如何学Gounsure if doing so would be considered bad practice/habit.
Should I suck it up and stick with using the octothorpe syntax or is this truly a matter of preference?
It would be very bad practise and an extremely unreliable method of referring to DOM Elements.
Take the following example:
var myDiv = 'blahblahblah';
$(myDiv).hide();
This will translate into:
$('blahblahblah').hide();
Which isn't what you want.
$('#myDiv').hide();
will always work.
It is also a non-standard tradition for element ID's to be presented in the JavaScript scope; so don't rely on it!
Your later statement only works because you have a myDiv variable, or because you're inside a with statement, or something like that. It will not work under normal conditions. So to answer your question, you do need to use the first syntax all the time ... unless you happen to have a variable like:
var myDiv = document.getElementById("myDiv");
or
var myDiv = "#myDiv";
Oh, and I almost forgot: some browsers effectively wrap your code in a with statement for you; I forget which browsers exactly, but I think IE is the only one that does it. So you might not actually have a var or a with statement, but behind the scenes your browser is adding one (which means your code will only work on that browser, and not on others).
the second method you show would be used if you have a variable set to the div, such as
var myDiv = $('#myDiv');
or
var myDiv = '#myDiv';
hmmm, leaving out the # and quotes breaks the jQuery selector on my computer...I would view the source on your page and make sure your browser is not using a cached version of the page with the "#" still in the code.
As far as I understand it, $(mydiv) will select any < mydiv / > tags in your document, of which there are probably none =D
Andy
AFAIK, chucking in myDiv
like that in your last example relies a bit on browser nuances, and may break in some browsers.
What I fathom is an additional problem, is that this would cause conflicts if ever somewhere down the code you actually define a variable var myDiv = "foo";
or something. At least, with #myDiv
syntax, you're explicit about wanting to select something by ID.
精彩评论