我试图使用以下功能切换我的radio按钮-- true或false。
但作为第一次点击,我没有得到任何回应。稍后它可以正常工作。现在要解决这个问题,这里有什么问题吗?
var switching = false;
$('button').on("click", function() {
switching = switching == false ? switching = true : switching = false;
console.log("switching", switching); //first click true but not works!
$(":radio").attr("disabled", switching);
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>
<button>
Switch Me
</button>
现场演示
发布于 2017-04-19 10:51:18
您可以从true开始,然后像这样切换switching = !switching
var switching = true;
$('button').on("click", function() {
switching = !switching
$(":radio").attr("disabled", switching);
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>
<button>
Switch Me
</button>
发布于 2017-04-19 10:58:30
或者你只需一行就可以做到:
$('button').on("click", function() {
$(":radio").prop('disabled', function(){ return !this.disabled });
});button.border { border:2px solid green; }<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>
<button>Switch Me</button>
发布于 2017-04-19 10:52:02
您的三元操作符不正确,应该是:
switching = switching == false ? true : false;所以你的代码变成:
变量切换=假;
$('button').on("click", function(){
switching = switching == false ? true : false;
console.log( "switching", switching );
$(":radio").attr("disabled", switching);
})但是第一次单击将不起作用,因此您需要将其初始化为true。
var switching = true;
$('button').on("click", function(){
switching = switching == false ? true : false;
console.log( "switching", switching );
$(":radio").attr("disabled", switching);
})button.border{
border:2px solid green;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="foo" value="Y" checked disabled>
<input type="radio" name="foo" value="N" disabled>
<input type="radio" name="foo" value="X" disabled>
<button>
Switch Me
</button>
https://stackoverflow.com/questions/43493535
复制相似问题