[英]Change class of li to active class
For styling purposes im using a UL and li class to hold some form selection options. 出于样式目的,im使用UL和li类持有一些表格选择选项。 Im going to make the radio button hidden and then use the value on form submit.
我将隐藏单选按钮,然后使用表单提交中的值。 I figured out how to check the radio box when the
<li>
is clicked but for some reason the selected class isnt added to the <li>
which holds the radio button. 我想出了如何在单击
<li>
时检查单选框,但由于某种原因,所选类未添加到保存单选按钮的<li>
中。
Heres the code: 这是代码:
<ul class="options-num">
<li><input type="radio" name="group1" value="2000"> 2,000</li>
<li><input type="radio" name="group1" value="2000"> 4,000</li>
<li><input type="radio" name="group1" value="2000"> 6,000</li>
<li><input type="radio" name="group1" value="2000"> 8,000</li>
<li><input type="radio" name="group1" value="2000"> 10,000</li>
</ul>
Below is my javascript, this works for setting radio as checked when li is clicked but doesnt set selected class: 以下是我的JavaScript,这适用于在单击li而不设置选定的类时将收音机设置为选中状态:
$(".options-num > li").click(function(){
$(".options-num > li").find('input[type="radio"]').removeAttr('checked');
if($(this).find('input[type="radio"]').attr('checked','checked')) {
$(this).parent().addClass("selected");
}
});
This is what i tried first but didnt work 这是我首先尝试但没有成功的方法
$('.options-num li').click(function(){
var radio = $(this).children('input[type=radio]');
if (radio.is(':checked')) {
$(this).parent().addClass("selected");
//$("#foo").toggleClass(className, addOrRemove);
//$(this).('.options-num li').addClass('selected');
} /*else {
$(this).parent('li').removeClass('selected');
}
})
here is a solution: 这是一个解决方案:
https://jsfiddle.net/bb6fp28p/ https://jsfiddle.net/bb6fp28p/
<ul class="options-num">
<li><input type="radio" name="group1" value="2000"> 2,000</li>
<li><input type="radio" name="group1" value="2000"> 4,000</li>
<li><input type="radio" name="group1" value="2000"> 6,000</li>
<li><input type="radio" name="group1" value="2000"> 8,000</li>
<li><input type="radio" name="group1" value="2000"> 10,000</li>
</ul>
CSS: CSS:
.selected{
background:green;
}
JS JS
$('.options-num li').click(function(){
$('.options-num li').removeClass('selected');
$(this).addClass('selected');
$(this).find('input').prop('checked', true);
});
The .attr('checked','checked')
is setting the attribute of the element. .attr('checked','checked')
正在设置元素的属性。
Use .prop('checked')
and the problem should be fixed! 使用
.prop('checked')
并且问题应该得到解决!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.