[英]use JQuery to find the collective radio button group name
我最近问过很多jQuery问题,因为我正在尝试使用它相当好的旧Javascript,正如我在之前的问题中所提到的那样,“我目前不得不扩展一个非常古老的ASP.NET站点,它生成了一个数据库前端并且是应用程序的庞然大物,它需要完全重写 - 但是我被告知要添加它而不是重新开发它“
现在我正在做的是,一旦后端将表格呈现给我希望循环遍历表格的tr元素的接口,在tr的td元素之一中有两个单选按钮。 我需要确定单选按钮组的名称,因为我没有定义它们,系统是否使用GUID或其他东西?
这是表格,例如......
<table id="tableID">
<tr>
<td class="qCol">
<!-- Label here -->
</td>
<td class="qCo2">
<!-- img here -->
<!-- and a text box -->
</td>
<td class="qCo3">
<!-- select menu here -->
</td>
<td class="qCo4">
<!-- radio buttons here -->
</td>
<td class="qCo5">
<!-- select menu here -->
</td>
<td class="qCo6">
<!-- hidden validation image here -->
</td>
<tr>
</table>
好吧,我循环遍历表,同时将一个单元格的innerHTML切换到另一个单元格并隐藏一些行,我将添加功能以便稍后显示这些,这里是jQuery:
$('#tableID tr').each(function (i) {
/*switch select and validation and clear */
$(this).children('td.qCol').html($(this).children('td.aCol5').html());
$(this).children('td.aCol5').html($(this).children('td.vCol'.html(""));
/* hide all but the first row*/
if (i >= 1) {
$(this).hide();
}
现在我正在尝试确定将在类.qCo4的单元格中的单选按钮的name属性,但是我没有运气,因为以下返回错误并且是“未定义”...
/* get the radio button name and check if either are selected*/
// check something exists...
if ($('input:radio', this).attr('name')) {
var thisRadioName = $(this).closest("input:radio").attr('name').val();
alert(thisRadioName);
}
$this
是tr
元素,所以我应该使用child而不是最接近? 如果这没有意义,我可以更好地扩展和解释。
你应该使用find()
或children()
。 closest()
在树上,而find在树下查找元素
var thisRadioName = $(this).find("input:radio").attr('name');
您也可以使用':checked'来检查是否有任何收音机被检查
var checkedRadio = $(this).find("input:radio:checked")
如果您完全确定要查找的元素是元素的直接子元素,则应使用子元素,否则使用find()。 (如果你修改了html,使用find会保护你免受重构代码的影响,就像添加包装div一样,因为其他原因如styiling)
看看这个小提琴: http : //jsfiddle.net/nicolapeluchetti/Evq6y/
var thisRadioName = $(this).find("input:radio").attr('name');
应该做你想做的事
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.