两个变量看起来一样,除了其中一个使用 replace() 并使其不起作用。
<div id="h|1.1|Name!7">1.NOT CHANGED</div>
<div id="h|1.1|Title!7">2.NOT CHANGED</div>
var id = 'h|1.1|Name!7';
id = id.replace(/\./g,'\\\\.');
id = id.replace(/\|/g,'\\\\|');
id = id.replace(/\!/g,'\\\\!');
console.log(id); // all good
$("#" + id).text('1.CHANGED'); // not working
// when not using replace(), it works
var otherId = 'h\\|1\\.1\\|Title\\!7';
$("#" + otherId).text('2.CHANGED');
http://jsfiddle.net/L83ba7zg/1/
怎么会?
最佳答案
代码中的每个 \\\\
都应该只是 \\
。控制台输出可能看起来不错,但这是错误的:控制台每两个反斜杠只显示一个反斜杠。如果您登录 otherId
,您会得到不同的结果。
var id = 'h|1.1|Name!7',
otherId = 'h\\|1\\.1\\|Title\\!7';
// More concise version of replacements:
id = id.replace(/(\.|\||\!)/g,'\\$1');
// Now in the same format:
console.log(id); // "h\|1\.1\|Name\!7"
console.log(otherId); // "h\|1\.1\|Title\!7"
关于javascript - 在使用 .replace() 之后,字符串无法选择元素(使用 jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32108568/