4

我对动态生成的字段有疑问。这些字段有不同的类型,它们的类型取决于我的数据库中存储的内容(文本、选择、收音机等)。它们是在我的 PHP 脚本中生成的,并且它们具有相同的名称(ans[],它是一个数组)。

<input type='radio' name='ans[]' value='1'>
<input type='radio' name='ans[]' value='2'>
<input type='radio' name='ans[]' value='3'>

<select name='ans[]'>
    <option value='desktop'>Desktop</option>
    <option value='laptop'>Laptop</option>
    <option value='monitor'>Monitor</option>
    <option value='printer'>Printer</option>
</select>

<input type='text' name='ans[]' value=''>

我想使用 JQuery 获取每个字段的输入值。可能吗?

4

2 回答 2

2
$("[name=ans\\[\\]]").each(function() {
  alert( $(this).val() );
});

这应该有效。

JSFiddle

上面的工作示例。

于 2013-04-26T03:04:34.337 回答
1

There's a number of ways you can get your field values with jQuery that doesn't rely on IDs or classes (although they're usually the best methods).

You can select fields based on their position in the DOM:

CSS nth-child (http://www.w3schools.com/cssref/sel_nth-child.asp)

$('form#myform input:nth-child(2)')

jQuery .each (http://api.jquery.com/jQuery.each/)

$('form#myform input).each( function(){ /* functionality here */ });

This relies on the fields being generated in a fixed order though. What if you generated a label with each of your PHP array items, and used this to identify your individual fields?

于 2013-04-26T03:05:39.673 回答