我有一张产品选项表,每个 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 时, radio 输入周围会出现一个跨度,.checked
类会添加到该跨度中以切换选中/未选中样式。仅当您直接单击输入时,此情况才会发生变化。因此,我还需要考虑与 tr.selected
类类似的脚本,以便当单击 tr
的任何部分时,自定义单选按钮也具有更新的类。
JavaScript 生成的 radio 的引用标记是:
<div class="radio">
<span>
<input type="radio" name="" />
</span>
</div>
编辑:这是一个包含uniform.js的CodePen,它应该更好地演示问题:
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');
});
这应该找到所有 radio 并将它们全部设置为 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));
});
});
关于javascript - 单击表行时更新子元素类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35343032/