问题描述
在jQuery选择器中转义方括号的这些不同方式之间有什么区别.
是对是错,或者都是正确的吗?我已经阅读了不同的答案(包括 此 ),但没有人比较这种不同方式.
Is there a right or wrong way or are these both correct? I have read different answers (including this) but none compare this different ways.
HTML
<div name="name[1]"></div>
jQuery
$('div[name=name[1]]'); //wrong
$('div[name="name[1]"]'); //correct?
$('div[name="name\\[1\\]"]'); //correct?
$('div[name=name\\[1\\]]'); //correct?
我要求correct?
的所有工具都有效,使用选择器的方法/语法是否正确?
All those I ask correct?
work, is that ok way/syntax to use the selector?
我之前实际阅读过重复的建议答案,但不解释差异或应该使用的答案...我现在从该答案中得到了答案.
I read the duplicate suggested answer before I posted actually and it does not explain the differences or which should be used... I got that now from this answer.
推荐答案
除了第一个错误的情况:$('div[name=name[1]]');
,它引发错误unrecognized expression: div[name=name[1]]
-其他所有原因都可以使用,原因略有不同.
Apart from the first wrong case: $('div[name=name[1]]');
which throws a errorunrecognized expression: div[name=name[1]]
- all other are ok to use, because of slightly different reasons.
说明:
-
$('div[name="name[1]"]')
可以可以使用,因为jQuery将name[1]
视为字符串而不是CSS/jQuery选择器.因此无需逃脱.
$('div[name="name[1]"]')
is ok to use because jQuery treatsname[1]
as a string and not a CSS/jQuery selector. So no need to escape it.
$('div[name="name\\[1\\]"]')
,实际上没有必要转义,但可以使用. jQuery将name\\[1\\]
读取为字符串,并且在javascript中,第一个反斜杠\
转义第二个反斜杠,结果为\[
,这与[
相同.因此,此示例与前面的示例相同,只是带有不必要的反斜杠.
$('div[name="name\\[1\\]"]')
, is actually unnecessary escaped, but works. jQuery reads name\\[1\\]
as a string, and in javascript the first backslash \
escape the second which results \[
, and this is the same as [
. So this example is the same as the previous with unnecessary backslashes.
$('div[name=name\\[1\\]]')
还可以,并且内部的[]
应按需进行转义,因此不会混淆为CSS/jQuery选择器.
$('div[name=name\\[1\\]]')
is ok and the inner []
are escaped as they should so they will not be confused as CSS/jQuery selectors.
来自jQuery文档:
易于阅读:
- MDN - Escaping characters
- jQuery - Selectors
- W3.org - Characters
这篇关于这些在jQuery选择器中转义方括号的不同方法有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!