这里我有一个按钮,当用户单击它时,添加一个带有 2 个单选按钮是/否的问题,当用户选择一个值时,如果再次单击该按钮并添加新的单选按钮,它就会消失。我想要一个解决方案,即使单击按钮并添加新的 radioButton,选中的 radioButton 的值也将显示为选中状态。我试图使 id 标签变量,以便每个 radioButton 都有一个唯一的 id,但它没有任何区别。任何帮助将不胜感激。
<!DOCTYPE html>
<html>
<body>
<h1>Radio Buttons </h1>
<div id = "demo"> </div>
<br>
<button onclick="myFunction()"> add </button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML += '<br> agree? '+
'<br> <input type="radio" id="x"> yes' + ' <input type="radio" id="y"> No <br>';
}
</script>
</body>
</html>
最佳答案
innerHTML
将被覆盖!并且您将失去之前的输入
状态。
改为使用Element.insertAdjacentHTML()
<!DOCTYPE html>
<html>
<body>
<h1>Radio Buttons </h1>
<div id = "demo"> </div>
<br>
<button onclick="myFunction()"> add </button>
<script>
function myFunction() {
document.getElementById("demo").insertAdjacentHTML("beforeend", '<br> agree? '+
'<br> <input type="radio" id="x"> yes' + ' <input type="radio" id="y"> No <br>');
}
</script>
</body>
</html>
关于javascript - 添加另一个新单选按钮时如何保存单选按钮的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39509941/