查看了很多关于此的问题 - 但找不到真正的答案。所以这里...
我有一个表单,我将在其中动态添加部分(在本例中为“与会者信息”),因此我想使用像 firstName[0]
、firstName[1] 这样的名称
等。我已经编写了代码来为每个部分添加一个新的数字索引。
然而...
当我尝试使用 JQuery(或纯 JS)读取任何表单字段(动态创建或非动态创建)的值时,我得到了未定义。如果我将名称更改为 firstName1
、firstName2
等,它会起作用。仅当我使用数字数组索引时.. nada.
我试过...
$('#firstName[' + indexNum + ']')val();
$('input[name=firstName[' + indexNum + ']]').val();
.. 以及其他一些事情。 (是的,ID 与名称相同。)
有什么我想念的吗?
参见 Category:Attribute
Attribute values in selector expressions must follow the rules for W3C
CSS selectors; in general, that means anything other than a valid
identifier should be surrounded by quotation marks.
- double quotes inside single quotes:
$('a[rel="nofollow self"]')
- single quotes inside double quotes:
$("a[rel='nofollow self']")
- escaped single quotes inside single quotes:
$('a[rel=\'nofollowself\']')
- escaped double quotes inside double quotes:
$("a[rel=\"nofollow self\"]")
The variation you choose is generally a matter of style or
convenience.
尝试将属性值用单引号括起来 'firstName["+ indexNum + "]'
var indexNum = 0;
console.log($("input[name='firstName[" + indexNum + "]']").val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input name="firstName[0]" value="abc" />
或者使用两个反斜杠 \\
字符转义 [
和 ]
字符
var indexNum = 0;
console.log($("input[name=firstName\\[" + indexNum + "\\]]").val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input name="firstName[0]" value="abc" />