I have some kind of problem with jQuery selectors.
Let's say i want to select $('#elementID')
but the elementID
is a variable.
There is any other possiblity to do this other wa开发者_如何学Pythony than var variable = elementID; $('#'+variable)
? I mean without specifying the #
anywhere else?
Thanks!
The following is probably the fastest and the cleanest solution:
$(document.getElementById(elementID))
Appending your variable to "#" would work of course, but it's inherently slower.
Not really, no. You need "#" as a selector to select an ID. No reason to not use the ID selector. Or you could write your own function, something like:
$.id = function(id)
{
return $("#" + id);
}
var elementID = "elementID";
$.id(elementID).text();
That would return an element with the ID of "elementID" without having to use the "#". Kind of pointless though.
Not sure what you mean, but:
var variable = '#' + elementID;
$(variable)...
I use $('#'+variable) all the time.
If elementID is a variable ala var elementID = '#someId'
, I would suggest simply (although I didn't try it ):
$(elementID)
jQuery/JavaScript should dereference this variable as a string value and wrap the ID correctly for further operations...
精彩评论