问题描述
我在使用jQuery选择器时遇到了一些问题.
I have some kind of problem with jQuery selectors.
假设我要选择$('#elementID')
,但elementID
是变量.
Let's say i want to select $('#elementID')
but the elementID
is a variable.
除了var variable = elementID; $('#'+variable)
之外,还有其他方法可以执行此操作吗?我的意思是没有在其他任何地方指定#
吗?
There is any other possiblity to do this other way than var variable = elementID; $('#'+variable)
? I mean without specifying the #
anywhere else?
谢谢!
推荐答案
不是,不是.您需要#"作为选择器来选择ID.没有理由不使用 ID选择器.或者,您可以编写自己的函数,例如:
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();
这将返回ID为"elementID"的元素,而不必使用#".虽然没有意义.
That would return an element with the ID of "elementID" without having to use the "#". Kind of pointless though.
这篇关于ID/类别选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!