Javascript 使用带有变量的querySelector获取单选按钮值

Javascript 使用带有变量的querySelector获取单选按钮值,javascript,html,css,web-applications,Javascript,Html,Css,Web Applications,我试图使用querySelector获取单选按钮的选定值,但当我使用变量而不是实际键入名称时,它似乎不起作用 以下是我的HTML代码: <!DOCTYPE html> <head> <script src="allscripted.js" type="text/javascript"></script> <link rel="stylesheet" href="nostylist.css"/> </head> &

我试图使用querySelector获取单选按钮的选定值,但当我使用变量而不是实际键入名称时,它似乎不起作用

以下是我的HTML代码:

<!DOCTYPE html>

<head>
  <script src="allscripted.js" type="text/javascript"></script>
  <link rel="stylesheet" href="nostylist.css"/>
</head>

<body>

  <h1>HTML UI</h1>

  <table>
    <tr>
      <th>Statement A</th>
      <th>Agree much more with statement A</th>
      <th>Agree somewhat more with statement A</th>
      <th>Agree somewhat more with statement B</th>
      <th>Agree much more with statement B</th>
      <th>Statement B</th>
      <th>Reponse</th>
    </tr>


      <tr>
        <td>I am particular about the food that I eat</td>
        <td><input type="radio" name="row1" value="1" onclick="betterRadioButtons(1)"></td>
        <td><input type="radio" name="row1" value="2" onclick="betterRadioButtons(1)"></td>
        <td><input type="radio" name="row1" value="3" onclick="betterRadioButtons(1)"></td>
        <td><input type="radio" name="row1" value="4" onclick="betterRadioButtons(1)"></td>
        <td>I am not super-picky</td>
        <td id="r1"></td>
      </tr>

      <tr>
        <td>I eat whatever I want</td>
        <td><input type="radio" name="row2" value="1" onclick="betterRadioButtons(2)"></td>
        <td><input type="radio" name="row2" value="2" onclick="betterRadioButtons(2)"></td>
        <td><input type="radio" name="row2" value="3" onclick="betterRadioButtons(2)"></td>
        <td><input type="radio" name="row2" value="4" onclick="betterRadioButtons(2)"></td>
        <td>I carefully watch my diet</td>
        <td id="r2"></td>
      </tr>



  </table>


  <p id="testing"></p>
我的console.log(rowName)语句返回第1行,但出现以下错误:

未捕获的TypeError:无法读取null的属性“值”

然而,这是可行的:

function betterRadioButtons(num) {
    var rowName = "row" + num.toString();
    var resultName = "r" + num;
    var buttonVal = document.querySelector('input[name="row1"]:checked').value;
    document.getElementById(resultName.toString()).innerHTML = buttonVal;
    console.log(buttonVal);
    console.log(rowName);
    console.log(resultName);

}

任何帮助都将不胜感激

您需要包括引号,就像传递硬编码值时在第二个代码块中所做的那样
“row1”
。但是,由于您实际上希望传递一个变量(
rowName
),因此需要将选择器字符串与变量名连接起来

因此,不是:

var buttonVal = document.querySelector('input[name=rowName]:checked').value;
使用:

document.querySelector('input[name=“”+rowName+“]:checked')。值;
var buttonVal = document.querySelector('input[name=rowName]:checked').value;
var buttonVal = document.querySelector('input[name="' + rowName + '"]:checked').value;