Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why do I get this error and how can I test for it so it wont break, I tried checking for null but obviously that wont work, thanks.

Please don't advice to not write the ID like this as I know its wrong but it is a possibility.

var jsonTest = [
  {
    "myId": "''''''""""'''''''''''''"#####$'''''",
  }
];

alert(jsonTest[0].myId); 
// Works - alerts the myId

$('#' + jsonTest[0].myId ).length; 
// Error: Syntax error, unrecognized expression:
// #''''''""""'''''''''''''"#####$'''''
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
378 views
Welcome To Ask or Share your Answers For Others

1 Answer

jQuery's uses this code to detect an id based selector :

characterEncoding = "(?:\\.|[\w-]|[^\x00-\xa0])+"
...
"ID": new RegExp( "^#(" + characterEncoding + ")" ),

This regex fails for "''''''""""'''''''''''''"#####$'''''" or more simply for "'".

The query engine is limited, which isn't very surprising for a so concise language and id validity rules so lax. it can't handle any valid id.

If you really need to be able to handle any kind of valid id, use

$(document.getElementById(jsonTest[0].myId))

In fact, you should never use $('#'+id) as it simply adds a useless (and a little dangerous) layer of parsing for the same operation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...