gpt4 book ai didi

javascript - 使用带变量的 querySelector 获取单选按钮值

转载 作者:行者123 更新时间:2023-11-28 00:41:47 27 4
gpt4 key购买 nike

我正在尝试使用 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>

这是我的 JavaScript 代码:

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

}

我的 console.log(rowName) 语句返回第 1 行,但出现此错误:

未捕获的类型错误:无法读取 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;

使用:

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

关于javascript - 使用带变量的 querySelector 获取单选按钮值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53052925/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com