在jQuery变量中转义字符不起作用 [英] Escape characters in jQuery variables not working

查看:396
本文介绍了在jQuery变量中转义字符不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中使用选择器时,我遇到了在变量中发现的转义字符(即句点)的问题。我打算把它全部输出,但是在Chrome中我的控制台窗口的屏幕截图更容易。

I'm having issues with escaping characters (namely period) found in variables when using selectors in jQuery. I was going to type this all out, but it was just easier taking a screenshot of my console window in Chrome.

它看起来像变量和明文版本匹配。我希望 $('#'+ escName)返回div,就像 $('#jeffrey\\l.lamb')返回一个div。它不是。为什么?

It looks like the variables and the clear text versions match up. I expect $('#'+escName) to return the div, just like $('#jeffrey\\.lamb') returns a div. It does not. Why?

推荐答案

您必须考虑将检查字符串值的各个解析器。当然,第一个是JavaScript解析器本身。反斜杠字符在字符串语法中具有含义,因此,如果您希望在字符串中单个反斜杠需要加倍。

You have to think in terms of the individual parsers that will be examining your string values. The very first one, of course, is the JavaScript parser itself. Backslash characters have a meaning in the string grammar, so if you want a single backslash in a string it needs to be doubled.

从源代码解析字符串是一个内部的字符串值,接下来要注意它的内容(在这种情况下)是CSS选择器评估器(Sizzle或本机 querySelector 代码;不是确定在这样的字符串的情况下如此转义)。该代码只需要一个反斜杠来引用,以便它不被解释为引入类名匹配。

After the string is parsed from the source code into an internal string value, the next thing that'll pay attention to its contents (in this case) is the CSS selector evaluator (either Sizzle or the native querySelector code; not sure which in the case of strings with escapes like this). That code only needs one backslash to quote the . in order that it not be interpreted as introducing a class name match.

因此,在这种情况下,您需要的是 escName =jeffrey\\.lamb;

Thus, escName = "jeffrey\\.lamb"; is all you need in this case.

这篇关于在jQuery变量中转义字符不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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