Uncaught Error: Syntax error, unrecognized expression: #'10/12/2015'(…)

Uncaught Error: Syntax error, unrecognized expression: #'10/12/2015'(…)

这个 javascript 的字符串给我这个错误:未捕获错误:语法错误,无法识别的表达式:#'10/12/2015'(...)。

$("#10/12/2015").click();

怎么了?

谢谢 马库斯

您需要对选择器中的 / 进行转义。

$("#10\/12\/2015").val("aaaa");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="10/12/2015" />

jQuery 在他们的 selectors documentation page.

之上进行了解释

/ 字符不能在 CSS id 选择器中按字面意义使用。参见rules for CSS identifiers。此外,字符 1 不能用作 id 选择器的第一个字符。

如果你确实有那个日期 id 的元素,你可以使用属性选择器:

$('[id="10/12/2015"]').click();

或者,getElementById

$(document.getElementById("10/12/2015")).click();

或者,对 / 使用 CSS 转义,即 F\/,对 1 使用 </code> ](但不是 <code>);当然,这些反斜杠需要转义才能放入字符串中,所以:

$("#\31 0\2f 12\2f 2015").click();
// or
$("#\31 0\/12\/2015").click();

(我们需要空格,以便 CSS 解析器知道转义序列已经结束;否则忽略空格;它们是 not 解释为后代组合子。)

所有这些选项的实例,包括在 CSS 中使用它们来证明它们有效(而 #1... 无效):

$("input[type=button]").on("click", function() {
  log("Clicked");
});

log("With an id selector:");
$('[id="10/12/2015"]').click();

log("With getElementById:");
$(document.getElementById("10/12/2015")).click();

log("With escaped 1 and slashes:");
$("#\31 0\2f 12\2f 2015").click();

log("With escaped 1 and the other kind of escaped slashes:");
$("#\31 0\/12\/2015").click();

function log(msg) {
  $("<p>").text(msg).appendTo(document.body);
}
[id="10/12/2015"] {
  color: blue;
}

# 0f 12f 2015 {
  border: 1px solid black;
}

# 0\/12\/2015 {
  font-size: 20px;
}

/* Proof that the one starting with 1 is invalid: */
#10\/12\/2015 {
  text-decoration: line-through;
}
<p>Note that the button has blue text, a black border, and a 20px font. Those are applied by three diffent CSS rules, using the various selectors described in the answer. Note that it <em>isn't</em> strikethrough, proving that a selector starting with 1 is invalid.</p>
<input type="button" id="10/12/2015" value="Click Me">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>