[英]else block in if statement is never reached
I know there are many similar questions on IF statements, but I haven't found one specific to my case 我知道IF语句上有很多类似的问题,但我还没有发现一个特定的问题
I can't see why the else block is never hit when the condition should be toggling between true and false 我不明白为什么当条件应该在true和false之间切换时,else块永远不会被命中
document.getElementById("outlineCheck").addEventListener("click", function() { if (document.getElementById("outlineCheck").checked == true) { document.getElementById("outlineCheck").checked = false; } else { console.log("hit") document.getElementById("outlineCheck").checked = true; } });
<label><input asp-for="CourseOfferingOverviewFlag" value="1" id="outlineCheck" type="radio" />
It never gets to the else
because you always undo what the user did. 它永远不会给
else
,因为你随时撤消用户做了什么。
The button is initially unchecked. 该按钮最初未被选中。 When the user clicks on the button, it gets checked, so you go into the
if
block and uncheck the button. 当用户单击该按钮时,它将被选中,因此您进入
if
块并取消选中该按钮。 The next time the user clicks on the button, the same thing happens. 下次用户单击按钮时,会发生相同的事情。
As @Barmar answer you are unchecking the checkbox all the time. 作为@Barmar答案,您一直都在取消选中该复选框。
If you are trying to do something in checked or unchecked mode, I think you can do like this to have access to both conditions: 如果您尝试以检查或非检查模式执行某项操作,那么我认为您可以这样做来访问这两种情况:
PS Try to cache your DOM access for better performance. PS尝试缓存DOM访问以获得更好的性能。
Example 例
var $checkbox = document.getElementById("outlineCheck"); $checkbox.addEventListener("click", function() { if ($checkbox.checked) { console.log('Now is checked') } else { console.log('And now is unchecked') } });
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <input type="checkbox" id="outlineCheck">TEST </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.