jQuery $('input[type=radio]:checked') 的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6673951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Event for $('input[type=radio]:checked')
提问by Coisox
This is my jQuery script:
这是我的 jQuery 脚本:
$("input[type=radio]:checked").live("click", function() {
$(this).attr("checked",false);
});
I want to make all my radio button can be checked and unchecked. The code suppose to trigger ONLY when checked radio being clicked. But somehow, any radio click (whether it's checked or not) will trigger this event. It's as if the browser will check the radio first and then run my script.
我想让我所有的单选按钮都可以被选中和取消选中。该代码假设仅在单击选中的无线电时触发。但不知何故,任何无线电点击(无论是否选中)都会触发此事件。就好像浏览器会先检查收音机,然后运行我的脚本。
If I alert($("input[type=radio]:checked").size())
, it gave me the correct count.
如果 I alert($("input[type=radio]:checked").size())
,它给了我正确的计数。
I'm testing the code in FF4 but I hope the solution can cater for IE as well.
我正在 FF4 中测试代码,但我希望该解决方案也能满足 IE 的需求。
Ok, since my question seems confusing, this is the working code for what I want, BUT it requires additional custom attribute which I hope can avoid.
好的,因为我的问题似乎令人困惑,这是我想要的工作代码,但它需要额外的自定义属性,我希望可以避免。
<input type="radio" name="group1" value="1" isChecked="false"/>
<input type="radio" name="group1" value="2" isChecked="false"/>
<input type="radio" name="group1" value="3" isChecked="false"/>
<script>
$(document).ready(function(){
$("radio").click(function(){
if($(this).attr("isChecked")=="false"){
$(this).attr("isChecked","true");
$(this).attr("checked",true);
}
else{
$(this).attr("isChecked","false");
$(this).attr("checked",false);
}
});
});
</script>
回答by FishBasketGordo
This isn't really the way that radio buttons are intended to be used. It seems like you are trying to create an input control that's somewhere between a radio button and a checkbox.
这并不是单选按钮的真正用途。您似乎正在尝试创建一个介于单选按钮和复选框之间的输入控件。
There are a couple of approaches you could take:
您可以采取以下几种方法:
1) Use a separate button to clear the radio buttons:
1) 使用单独的按钮清除单选按钮:
The HTML:
HTML:
<input id="clearRadios" type="button">Clear</input>
The jQuery:
jQuery:
$('#clearRadios').click(function() {
// use attr only if you're using an older version of jQuery
$('input[type=radio]').prop('checked', false);
});
2) Use checkboxes rigged to work like radio buttons:
2)使用被操纵的复选框像单选按钮一样工作:
var $chkboxes = $('input[type=checkbox]');
$chkboxes.click(function() {
var currChkbox = this;
$chkboxes.each(function() {
if (this !== currChkbox) {
$(this).prop('checked', false);
}
});
});
If it were me, I'd probably go with the first option in most circumstances.
如果是我,大多数情况下我可能会选择第一个选项。