jquery选择一个项目
问题描述:
我有一个表格的形式。jquery选择一个项目
<form >
<div>
<table>
<tr>
<td > <input type="text" id="slno1" size="25" value="10" /> </td>
<td > <input type="text" id="data" size="10" value="this is a test" /> </td>
<td > <input type="radio" value="" id="edit1" name="sample" /> </td>
</tr>
<tr>
<td > <input type="text" id="slno2" size="25" value="10" /> </td>
<td > <input type="text" id="data1" size="10" value="this is a test1" /> </td>
<td > <input type="radio" value="" id="edit1" name="sample" /> </td>
</tr>
</table>
<input type="submit" id="mysu1" Value="submits" />
</div>
</form>
因为当用户选择一个单选按钮的行时,我需要该行上的所有数据。 所以,我们做的:
var theSelectedRadioButton = theForm.find('input[name="sample"]:checked');
我怎样才能在TD的所有相应的值。
答
您可以使用closest
单选按钮,找到tr
它在,然后children
找到所有的td
s表示行中:
var tds = theSelectedRadioButton.closest('tr').children('td');
然后从td
s撷取的信息,可能在使用each
或map
的循环中。你还没有说哪里的信息,但对于例如,如果你希望自己的HTML:
var tdhtml = theSelectedRadioButton.closest('tr').children('td').map(function(td) {
return $(this).html();
}).get();
...结果字符串数组中tdhtml
包含每个td
的HTML。 (注意在结束时容易错过呼叫get
:map
返回即使它的内容不是DOM元素jQuery对象,get
将其转换成正常阵列。)
可替换地,如果信息被存储在在td
小号data-*
属性(在这个例子中data-foo
):
var tddata = theSelectedRadioButton.closest('tr').children('td').map(function(td) {
return $(this).attr('data-foo');
}).get();
答
var theSelectedRow = theSelectedRadioButton.closest('tr');
应该给你行,从那里你可以在该行中访问数据。
另外:你可以将数据处理函数绑定到单选按钮,那么你不需要“找到”它。
答
当目标输入字段的值发生变化,你可以找到使用.closest()
找到合适的行,然后收集每个孩子的值到一个新的对象。
$(theForm).find('input[name="sample"]').change(function() {
var vals = $(this).closest('tr').children('td').map(function() {
return $(this).find('input').val();
}).toArray();
});
谢谢我也更新了表单数据。当我保持警觉时,我得到:tds作为对象对象..比这更容易 –
@TheLearner:对,'tds'是一个对象。它是一组匹配的'td'元素的jQuery包装器。我向你展示了如何从这些元素中提取信息(作为数组)。强烈建议不要使用'alert'这个东西。所有主流浏览器都至少内置了一个体面的调试器:http://blog.niftysnippets.org/2011/03/no-excuse.html使用适当的工具,您可以检查内容'tds' /'tdhtml' /'tddata'甚至(有几个)使用交互式代码来找出如何处理它。 –