Escape characters in jQuery variables not working

99封情书 提交于 2019-12-12 05:39:03

问题


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.

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?


回答1:


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.

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.

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



来源:https://stackoverflow.com/questions/37844324/escape-characters-in-jquery-variables-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!