简体   繁体   English

.checked 总是返回 true?

[英].checked always returns true?

I'm using vanilla js, and I'm stumped because there's very little code here, so I'm not sure where the problem lies.我使用的是 vanilla js,我很难过,因为这里的代码很少,所以我不确定问题出在哪里。 It may be a misunderstanding on my part on how the attribute works.这可能是我对属性如何工作的误解。

 function changeState() { const self = event.target const parent = event.path[1] if (self.type == "radio") { console.log(self.id + " is " + self.checked) } }
 <div id="usernames_buttons"> <input type="radio" name="usernames" id="usernames-bl" onclick="changeState()" checked> <label for="usernames-bl">BL</label> </input> <input type="radio" name="usernames" id="usernames-wl" onclick="changeState()"> <label for="usernames-wl">WL</label> </input> <button data-toggle onclick="changeState()">OFF</button> </div>

I paired everything down to just this code and ran it in a code pen to test, and the console.log will return true regardless of which option I am clicking.我将所有内容与此代码配对并在代码笔中运行以进行测试,无论我单击哪个选项,console.log 都将返回 true。 The expectation is that usernames-bl would return true and -wl would return false, but they return true whether the checked attribute is there or not.期望 usernames-bl 将返回 true 而 -wl 将返回 false,但无论是否存在已检查的属性,它们都会返回 true。

您在每次点击时都调用 changeState() ,我猜它是一个单选按钮,它总是在点击时提供选中的“true”

I think you are doing it right minus the "Off" button should un-check both.. so I added this block:我认为您做得对,减去“关闭”按钮应该取消选中两者..所以我添加了这个块:

if (self.type != "radio") {
    document.getElementById("usernames-wl").checked = false;
    document.getElementById("usernames-bl").checked = false;
  }

 function changeState() { const self = event.target const parent = event.path[1] if (self.type != "radio") { document.getElementById("usernames-wl").checked = false; document.getElementById("usernames-bl").checked = false; } console.log("usernames-wl is " + document.getElementById("usernames-wl").checked) console.log("usernames-bl is " + document.getElementById("usernames-bl").checked) }
 <div id="usernames_buttons"> <input type="radio" name="usernames" id="usernames-bl" onclick="changeState()" checked/> <label for="usernames-bl">BL</label> <input type="radio" name="usernames" id="usernames-wl" onclick="changeState()"/> <label for="usernames-wl">WL</label> <button data-toggle onclick="changeState()">OFF</button> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM