javascript - 使用JQuery查找集体单选按钮组名

标签 javascript jquery

我最近问了很多 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 的单元格中,但是我没有运气,因为以下返回错误并且是“未定义的”...

/* 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);

}

$thistr 元素,所以我应该使用 child 而不是 closest 吗?如果这没有意义,我可以进一步扩展和解释。

最佳答案

您应该使用find()children()closest() 在树上查找,而 find 在树下查找元素

var thisRadioName = $(this).find("input:radio").attr('name');

你也可以使用 ':checked' 来检查是否有任何 radio 被选中

var checkedRadio = $(this).find("input:radio:checked")

如果您绝对确定要查找的元素是该元素的直接子元素,则应使用子元素,否则使用 find()。 (如果您修改 html,使用 finds 可以保护您免于重构代码,例如出于样式等其他原因添加包装 div)

看看这个 fiddle :http://jsfiddle.net/nicolapeluchetti/Evq6y/

关于javascript - 使用JQuery查找集体单选按钮组名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6844516/

相关文章:

javascript - meteor .js : How to get the name of a Template from the Template?

javascript - 如果按钮被按下 10 秒按钮功能?

javascript - 使用过渡效果更改文本(缩放/淡入淡出)

javascript - 请帮助理解功能

javascript - Node js : POST/GET method isn't working when called by AJAX

javascript - 如何在 ExtJS 或 JavaScript 中将字符串转换为 Unix 时间戳?

javascript - 当页面滚动到页脚时,如何使我的粘性侧边栏向上滚动?

javascript - 如何使用 jQuery 仅检索隐藏输入上逗号分隔值中的第二项

c# - 在 MVC 中按字母顺序排列 SelectList

javascript - 从两个数组创建对象