单击 table 行时更新子元素 类

Updating child element classes when table row is clicked

我有 table 个产品选项,每个 tr 个选项。一个是默认 selected,另一个是 select,在提交表单之前必须选中单选按钮。这很简单,但整个 tr 必须是可点击的并相应地选中单选按钮。

认为我已经设法使用下面的脚本让它工作:

$('.product-options tr').click(function() {
    $(this).find('td input[type=radio]').prop('checked', true);
});

除此之外我还需要在tr中添加一个.selected的class。我尝试使用以下代码,但我还需要检查另一个 tr 是否已经具有 .selected 的 class 并将其删除。

$('.product-options tr').click(function() {
    $(this).find('td input[type=radio]').prop('checked', true);
    $(this).toggleClass('selected', true);
});

显然,如果您单击同一个单选按钮,这只会切换 class。这是我有限的 javascript 知识不足之处。有人可以帮忙吗?

最后,我还使用了一个名为 uniform.js 的插件,它允许 selects/radio/checkboxes 完全可定制。当它包装一个 div 时,一个围绕无线电输入的跨度 .checked 的 class 被添加到跨度以切换 checked/unchecked 样式。这只有在您直接单击输入时才会改变。因此,我还需要考虑与 tr.selected class 类似的脚本,因为当 tr 的任何部分被单击时,自定义单选按钮也有一个更新的 class.

javascript 生成的收音机的参考标记是:

<div class="radio">
    <span>
        <input type="radio" name="" />
    </span>
</div>

编辑:这是一个包含 uniform.js 的 CodePen,应该可以更好地展示问题:

http://codepen.io/moy/pen/yeGRmO

谢谢,真的希望有人能帮忙解决这个问题。它 似乎 很简单......但是因为它 'layered up',我有点迷路了! :)

如果我理解正确,您可以简单地访问 tr 的兄弟姐妹并将选中的无线电设置为 false。

$('.product-options tr').click(function() {
    $(this).find('td input[type=radio]').prop('checked', true);
    $(this).toggleClass('selected', true);
    $(this).siblings().find('td input[type=radio]').prop('checked', false);
    $(this).siblings().removeClass('selected');
});

这应该找到所有收音机并将它们全部设置为 false,除了您单击的行。

更新

要使用制服,您可以在更改属性时直接调用 $.uniform.update()

$(function() {
    $('input[type="radio"]').uniform();

    $('.product-options tr').click(function() {
        var tr = $(this),
            radio = tr.find('td input[type=radio]'),
            siblings = tr.siblings(),
            otherRadios = siblings.find('td input[type=radio]');

        tr.addClass('selected');
        siblings.toggleClass('selected', false);

        $.uniform.update(radio.prop('checked', true));
        $.uniform.update(otherRadios.prop('checked', false));
    });
});

DEMO

试试这个:

$('.product-options tr').click(function () {
            $(this).find('td input[type=radio]').prop('checked', true);
            $(this).closest('table').find('tr.selected').find('span.checked').removeClass('checked');
            $(this).closest('table').find('tr.selected').removeClass('selected');
            $(this).addClass('selected'); $(this).find('td:last').find('span').addClass('checked');
        });

Check This Link