jquery selector doesnt accept pipe character |?

心不动则不痛 提交于 2019-12-28 06:33:15

问题


I have an html ID I'm trying to call. It has a specific name build like this name_|_anyting but when I try to get the elemetn using Jquery's selectors I get an error

$("#name_|_anyting")

Error: Syntax error, unrecognized expression: |_anyting

so my question is : Are pipe characters not allowed as Ids in jquery selectors ?


回答1:


| is a special character in selector syntax, which means you can't use it directly in an ID selector. If you cannot change the ID in your markup to accommodate your selector, you'll have to make do with escaping the selector to trick jQuery into selecting the element anyway:

$("#name_\\|_anything")



回答2:


Pipe character "|" has to be escaped using double backslashes.

Selectors

Borrowing from CSS 1–3, and then adding its own, jQuery offers a powerful set of tools for matching a set of elements in a document.

If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~**** ) as a literal part of a name, you must escape the character with two backslashes: \\. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.

http://api.jquery.com/category/selectors/




回答3:


To update an old question... In jQuery 3.0 you can now use $.escapeSelector(selector). Examples:

$('#' + $.escapeSelector('crazy|id.selector') + 'Wrapper').show();
$('.' + $.escapeSelector(divClassVariable)).each(function() {...})

and (from the docs)

$( "div" ).find( "." + $.escapeSelector( ".box" ) );


来源:https://stackoverflow.com/questions/12306252/jquery-selector-doesnt-accept-pipe-character

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