Javascript 如何在没有表单的情况下遍历单选按钮组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3473117/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:47:11  来源:igfitidea点击:

How to loop through a radio buttons group without a form?

javascriptjqueryhtmlradio-button

提问by Bart

How do I loop through a radio buttons group without a form in JavaScript or jQuery?

如何在没有 JavaScript 或 jQuery 表单的情况下遍历单选按钮组?

回答by Daniel Vassallo

What about something like this? (using jQuery):

这样的事情怎么办?(使用jQuery):

$('input:radio').each(function() {
  if($(this).is(':checked')) {
    // You have a checked radio button here...
  } 
  else {
    // Or an unchecked one here...
  }
});

You can also loop through all the checked radio buttons like this, if you prefer:

如果您愿意,您还可以循环浏览所有选中的单选按钮:

$('input:radio:checked').each(function() {
   // Iterate through all checked radio buttons
});

回答by bmaupin

...in case someone wants to do this without jQuery (since it was part of the question):

...如果有人想在没有 jQuery 的情况下执行此操作(因为它是问题的一部分):

I'm not sure what you mean by without a form. If you mean you don't want to pass the form element to a javascript function, you could do it like this:

我不确定你所说的没有表格是什么意思。如果您的意思是不想将表单元素传递给 javascript 函数,您可以这样做:

for (var i = 0; i < document.form_name.radio_name.length; i++) {
    if (document.form_name.radio_name[i].checked) {
        // ...
    }
}

If you mean without a form as in you have no form node, you could wrap them in a span (or a div) and use code like this:

如果您的意思是没有表单,因为您没有表单节点,则可以将它们包装在一个跨度(或一个 div)中并使用如下代码:

var span = document.getElementById("span_id");
var inputs = span.getElementsByTagName("input");
for (var i = 0; i < inputs.length; ++i) {
    if (inputs[i].checked) {
        // ...
    }
}

回答by Razor Storm

I can't be too sure what you mean but if you want to do something to all radio buttons on a page you can do this:

我不太确定你的意思,但如果你想对页面上的所有单选按钮做一些事情,你可以这样做:

$("input:radio").each(function(){
   //do something here
});