使用特殊字符查找元素时,如下$("#search@")
会出现异常。如何解决?
我试过使用所有特殊字符,但它正在使用 *
字符,如 $("#search*")
没有任何错误,但其他字符 #$% ^&()
抛出一个错误。那么为什么它接受 * 字符而另一个字符不接受。
最佳答案
如果您对 id
有特殊字符,您应该在访问它们时使用 \\
(两个反斜杠)对它们进行转义。但据我所知,只有 html5
才允许这样做。
如 jquery
中所述 selector documentation
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar").
alert($("#search\\$").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="search$">Heh</div>
关于javascript - 为什么 jquery id 选择器不支持特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32101846/