【发布时间】:2018-03-10 11:17:56
【问题描述】:
我使用 JQuery 1.11 并希望对所有以 partitions0.instances0.natures 开头并以 typeCle 结尾的 ID 执行操作,例如:id="partitions0.instances0.natures0.typeCle"。然后我将影响那些与我选择的元素相同的值。但我的问题出在选择器上。
我已经尝试过很多东西,比如$('[id^='+instanceId'][id$=typesCle]') 有或没有双引号,但现在找不到正确的答案。错误是Uncaught SyntaxError: Invalid or unexpected token
所有jquery代码:
var instanceId = $(this).attr("id");
var natureId = $(this).attr("id");
var valeur = $(this).prop('value');
natureId = natureId.replace("typesCle", "nature").replace(/\./g, '\\\\.');
$('[id^='+ natureId +'][id$=typesCle]').each(){
this.val(valeur);
}
我也用它的值替换了变量来检查,我有同样的错误信息:
$('[id^=partitions0\\.instances0\\.nature][id$=typesCle]').each(){
console.log(valeur);
this.val(valeur);
}
html代码:
<div class="col-sm-6">
<select th:field="*{partitions[__${rowPartitionStat.index}__].instances[__${rowInstanceStat.index}__].typesCle}" class="form-control modRepInstance">
<option th:each="typeCle : ${allTypesCle}"
th:value="${typeCle}" th:text="${typeCle}">...</option>
</select>
</div>
【问题讨论】:
-
您可能需要转义
instanceId值中的.,以免 Sizzle 将它们解释为类选择器。 -
您当前的代码缺少
+并且有一个"$('[id^='+instanceId + '][id$=typesCle]')- 不确定这是您的实际代码还是 copypasta 错误。此外,如果您希望元素集合.val()只会针对第一个匹配项,您可能需要使用.each() -
在 ID 中使用
.不是一个好主意,因为它们在选择器中用于表示后面是类名。虽然您可以逃脱它们,但很不方便。 -
@Barmar : 这是 spring/thymeleaf 生成的 id,所以我认为我不能简单地更改它。
-
@jayjaypg22 您转义了选择器内的点而不是实际的 html 标识符。只需在您的
instanceId中将.替换为\\.即可。你也可以使用.replace()。
标签: javascript jquery spring-boot jquery-selectors thymeleaf