Why selector works in first example, but fails in second one? See jsfiddle .
<div id="hello[1][2]_world"> </div>
<textarea id="console"></textarea>
<script>
$(document).ready(function() {
//first example
$('#hello\\[1\\]\\[2\\]_world').html('01234'); //everything is OK
//second example
var iid = 'hello[1][2]_world';
iid = iid.replace(/[#;&,.+*~':"!^$[\]()=>|\/]/g, "\\\\$&");
$('#console').val(iid); //see in textarea, the same string as from first
$('#'+iid).html('56789'); //not working! whyyyyyyyy? :)
});
</script>
The first string is "actually" '#hello\\[1\\]\\[2\\]_world'
.
What happens is that you have to escape \\
s in the first case so that the $()
function receives \\[
and so on so that it knows that it should treat those characters as part of the id.
In the second case you're creating a string that's hello\\\\\\\\[1\\\\\\\\]\\\\\\\\[2\\\\\\\\]_world
(as you have 4 backslashes in the replacement!) that becomes, after the backslashes have been escaped, hello\\\\[1\\\\]\\\\[2\\\\]_world
.
You can confirm this by adding these lines at the end (look in the JS console):
console.log( iid );
console.log( 'hello\\[1\\]\\[2\\]_world' );
jQuery's FAQ has a nice solution for this that escapes all character that jQuery requires.
I like this nullsafe version of what they suggest:
function jqid (id) {
return (!id) ? null : '#' + id.replace(/(:|\.|\[|\]|,)/g, '\\$1');
}
See answers to these questions also:
jQuery selector value escaping
Need to escape a special character in a jQuery selector string
You don't need to double escape the second one:
<div id="hello[1][2]_world"> </div>
<textarea id="console"></textarea>
<script>
$(document).ready(function() {
//first example
$('#hello\\[1\\]\\[2\\]_world').html('01234'); //everything is OK
//second example
var iid = 'hello[1][2]_world';
iid = iid.replace(/[#;&,.+*~':"!^$[\]()=>|\/]/g, "\\$&");
$('#console').val(iid); //see in textarea, the same string as from first
$('#'+iid).html('56789'); //not working! whyyyyyyyy? :)
});
</script>
Because really \\[
is that symbol escaped. But in your first string you have to escape the \\\\
and in the second you are doing this \\\\\\\\
. If that makes sense.
That's not a valid ID, and as thus you're relying on undefined behaviour. See this question . Can I suggest using data attributes for storing arbitrary data instead of doing it in the ID?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.