如果我的HTML看起来像这样:
<td class="controlCell">
<input class="inputText" id="SearchBag.CompanyName" name="SearchBag.CompanyName" type="text" value="" />
</td>
Run Code Online (Sandbox Code Playgroud)
我怎么能用JQuery选择#SearchBag.CompanyName?我无法让它发挥作用,我担心这是打破一切的点.令人讨厌的是,重命名我所有的id将是很多工作,更不用说可读性的损失.
bob*_*nce 210
@Tomalak在评论中:
因为ID选择器必须以hash#开头,所以这里不应该有歧义
"#id.class"是一个有效的选择器,它需要一个id和一个单独的类来匹配; 它是有效的,并不总是完全冗余.
选择文字"."的正确方法.在CSS中是逃避它:"#id\.moreid".这曾经在一些旧的浏览器(特别是IE5.x)中引起麻烦,但所有现代桌面浏览器都支持它.
同样的方法似乎在jQuery 1.3.2中有效,尽管我还没有彻底测试过它; quickExpr不会提取它,但更复杂的选择器解析器似乎正确:
$('#SearchBag\\.CompanyName');
Run Code Online (Sandbox Code Playgroud)
Tom*_*lak 116
一个变体是这样的:
$("input[id='SearchBag.CompanyName']")
Run Code Online (Sandbox Code Playgroud)
Ble*_*der 30
如果使用document.getElementById以下内容,则无需转义任何内容:
$(document.getElementById('strange.id[]'))
Run Code Online (Sandbox Code Playgroud)
getElementById 假设输入只是一个id属性,因此点不会被解释为类选择器.
one*_*ros 17
简答:如果你有一个id =的元素"foo.bar",你可以使用选择器$("#foo\\.bar")
更长的答案:这是jquery文档的一部分 - 你可以在这里找到的部分选择器:http: //api.jquery.com/category/selectors/
您的问题在文档开头就已得到解答:
If you wish to use any of the meta-characters ( such as
!"#$%&'()*+,./:;?@[\]^`{|}~ )
as a literal part of a name, you must escape the character with
two backslashes: \\. For example, if you have an element with id="foo.bar",
you can use the selector $("#foo\\.bar"). The W3C CSS specification contains
the complete set of rules regarding valid CSS selectors. Also useful is the
blog entry by Mathias Bynens on CSS character escape sequences for identifiers.
当您的ID在变量中时,attr选择似乎是合适的:
var id_you_want='foo.bar';
$('[id="' + id_you_want + '"]');
Run Code Online (Sandbox Code Playgroud)