我需要使用DOM计算一些选中的单选按钮的值

I need to calculate the value of some checked radio buttons using DOM

本文关键字:单选按钮 计算 DOM      更新时间:2023-09-26

目前我的代码是:HTML

<input type="radio" name="age" value="0">1-25
<input type="radio" name="age" value="5">26-27
<input type="radio" name="age" value="7">28-29
<input type="radio" name="bmi" value="0">0-25
<input type="radio" name="bmi" value="0">26-30
<input type="radio" name="bmi" value="9">31-35

所以我需要得到选中的单选按钮的值并计算它们

Javascript是我得到的第一个答案

function CalculateValue(){
  //call getAgeValue(), getBmiValue() here and do desired calculations here
}
function getAgeValue()
{
    for (var i = 0; i < document.getElementsByName('age').length; i++)
    {
        if (document.getElementsByName('age')[i].checked)
        {
            return document.getElementsByName('age')[i].value;
        }
    }
}
function getBmiValue()
{
    for (var i = 0; i < document.getElementsByName('bmi').length; i++)
    {
        if (document.getElementsByName('bmi')[i].checked)
        {
            return document.getElementsByName('bmi')[i].value;
        }
    }

使用香草document.querySelector

function doCalculation(ageValue, bmiValue) {
    // whatever
    return ageValue + bmiValue;
}
function getRadioValue(radio_name) {
    return ( // parenthesis to let us do an OR
      document.querySelector('input[type="radio"][name="' + radio_name + '"]:checked')
      || // or if none is checked
      {} // so we don't get an error
    ).value;
}
function handlerForButton(e) {
    var age = +getRadioValue('age'),
        bmi = +getRadioValue('bmi'),
        foo = doCalculation(age, bmi);
    // do whateverwith foo
    console.log(foo);
}
// after elements exist
document.querySelector('input[type="button"][value="Calculate"]')
    .addEventListener('click', handlerForButton);

您可能会发现使用id 查找元素比使用其他属性查找元素更容易。这也将提高性能