gpt4 book ai didi

javascript - 如何在 Javascript 中比较 id

转载 作者:行者123 更新时间:2023-12-01 16:10:15 24 4
gpt4 key购买 nike

我试图比较一个简单的代码,如果用户点击按钮,输出将显示适当的答案,但我似乎找不到任何正确的方法。

<!DOCTYPE html>
<html>
<body>
<p>Gender</p>
<label><input type="radio" name="gender" id="male" value="Male">Male</label>
<label><input type="radio" name="gender" id="male" value="Female">Female</label>
<br>
<br>
<button onclick="myFunction()">Try it</button>
<p id="demo">
<script>
function myFunction() {
var x = document.getElementById("demo").value;
var m = document.getElementById("male").value;
var f = document.getElementById("female").value;
if(x === m)
x.innerHTML = "You are male.";
else if(x === f)
x.innerHTML = "You are female.";
}
</script>

</body>
</html>

最佳答案

你想要像下面这样的东西:

    <html>
<body>
<p>Gender</p>
<label><input type="radio" name="gender" id="male" value="Male">Male</label>
<label><input type="radio" name="gender" id="female" value="Female">Female</label>
<br>
<br>
<button onclick="myFunction()">Try it</button>
<p id="demo">
<script>
function myFunction() {
var x = document.getElementById("demo");
var m = document.getElementById("male").checked;
var f = document.getElementById("female").checked;
if (m)
x.innerHTML = "You are male.";
else if (f)
x.innerHTML = "You are female.";
}
</script>

</body>
</html>

首先你有两个男性输入的id,你希望女性输入是女性:

 <label><input type="radio" name="gender" id="female" value="Female">Female</label>

其次,您想知道单选按钮是否被选中,而不是它的值:

 var m = document.getElementById("male").value; // returns Male in your case
var m = document.getElementById("male").checked; // returns true or false depending on whether it's been checked

那么逻辑需要一点改动:

  if (m)  // they selected male
x.innerHTML = "You are male.";
else if (f) // they selected female
x.innerHTML = "You are female.";

关于javascript - 如何在 Javascript 中比较 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61865962/

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