javascript - 为什么函数 javascript 给我相同的值
问题描述
为什么当我希望每次选择其他单选按钮时函数都给我相同的值
<form>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
<button onclick="addSpan()">Try it</button>
</form>
这是功能
<script>
function addSpan() {
var female = document.getElementById("female");
var male = document.getElementById("male");
var other = document.getElementById("other");
if (document.getElementById("female").checked = true) {
document.body.innerHTML += '<span class="bullet">female</span> ';
}
else if (document.getElementById("male").checked = true) {
document.body.innerHTML += '<span class="bullet">male</span> ';
}
else {
document.body.innerHTML += '<span class="bullet">other</span> ';
}
}
resultat [在此处输入图像描述][1]
解决方案
用于=
代替===
function addSpan() {
var female = document.getElementById("female");
var male = document.getElementById("male");
var other = document.getElementById("other");
if (female.checked === true) { // when checking something is true/false use === not = as = assigns a new value and === is checking if it is equal, also use the variables you assigned at the start
document.body.innerHTML += '<span class="bullet">female</span> ';
}
else if (male.checked) { // You can actually shorthand this as an IF statement automatically checks for if its equal to true
document.body.innerHTML += '<span class="bullet">male</span> ';
}
else {
document.body.innerHTML += '<span class="bullet">other</span> ';
}
}
推荐阅读
- python - 在python中使用正则表达式拆分多个单词的字符串
- javascript - 错误:“无法读取未定义的属性“div””
- java - Spring Boot 导入额外的无扩展属性
- flutter - 如何下载 HLS 流视频文件并保存在本地存储中?
- elasticsearch - 弹性搜索聚合查找所有记录中是否存在字段
- javascript - 如何在使用 Axe-Puppeteer 加载页面时强制 selenium webdriver 不打开“SaveAs”对话框?
- php - 如何从 usnig Goutte Client for BotDetectCaptcha 获取 base64 中的媒体内容
- algorithm - 双向一对多映射的正确数据结构是什么?
- python - 如何在scrapy输出中保留换行符?
- javascript - 使用js和jq滚动播放和暂停两个或多个视频的代码