这些在jQuery选择器中转义方括号的不同方法有什么区别 [英] What is the difference between these different ways to escape square brackets inside jQuery selectors

查看:85
本文介绍了这些在jQuery选择器中转义方括号的不同方法有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 error unrecognized 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 treats name[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文档:

使用任何元字符(例如!#$%&'()* +,./:;< =>?@ [] ^`{|}〜)作为文字部分名称,必须使用两个反斜杠将其转义:\\.

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\.


易于阅读:

  • MDN - Escaping characters
  • jQuery - Selectors
  • W3.org - Characters

这篇关于这些在jQuery选择器中转义方括号的不同方法有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆