例如:
var a = "1234";
var b = "line1\\\\.5";
现在这行代码:
"#" + a + b;
输出这个字符串
"#1234line1\\.5"
当我像这样在选择器中输入它时:
$("#1234line1\\.5")
它显示了正确的元素
but $("#" + a + b)
没有
提前感谢您的任何建议
最佳答案
我很惊讶它在控制台中工作,id
选择器无效。 CSS id
selectors cannot start with a digit .不过你可以逃避它:
var a = "\\31 234"; // \\31 = 1, then you need the space to terminate the escape
var b = "line1\\.5"; // Removed a pair of \\ from this, I assume you
// don't have a backslash in the id
$("#" + a + b).html("Found it");
这有效,例如:Live Example
<div id="1234line1.5"></div>
<script>
(function() {
"use strict";
var a = "\\31 234";
var b = "line1\\.5";
$("#" + a + b).html("Found it");
})();
</script>
如果你在id
中确实有一个反斜杠,那么反斜杠的转义是\5c
,你在字符串文字中写成\\5c
,所以:Live Example
<div id="1234line1\.5"></div>
<script>
(function() {
"use strict";
var a = "\\31 234";
var b = "line1\\5c \\.5";
$("#" + a + b).html("Found it");
})();
</script>
关于javascript - 在 jQuery 选择器中传递 2 个变量时没有结果,但是当键入相同的字符串输出时它会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25846406/