单击表行时更新子元素类

Updating child element classes when table row is clicked

本文关键字:元素 更新 单击      更新时间:2023-09-26

我有一个产品选项表,每个tr都是一个选项。默认情况下选择一个,要选择另一个,必须在提交表单之前选中单选按钮。这很容易,但整个tr必须可单击并相应地检查单选按钮。

我想我已经设法使用以下脚本使其工作:

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

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

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

显然,这只会在您单击相同的单选按钮时切换类。这就是我有限的JavaScript知识失败的地方。谁能帮忙?

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

对于javascript生成的无线电的引用标记是:

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

编辑:这是一个带有制服的代码笔.js它应该更好地展示问题:

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

谢谢,真的希望有人能帮忙。这似乎很简单...但是当它"分层"时,我有点迷茫!:)

如果我理解正确,您可以简单地访问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,您可以在更改属性时直接调用 $.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));
    });
});

演示

试试这个:

$('.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');
        });

检查此链接