jquery - 满足jquery条件时隐藏div不起作用
问题描述
我有以下应该隐藏的div。
<div class="alert alert-danger alert-dismissible" style="display: none;" id="alertDiv"> <strong>Note!</strong><p>At the moment we cannot accept any players born 05 or earlier beacuse we currently are too many.</p></div>
当用户在文本字段“membership-form-personnumber”中输入数值时,我想用 jquery 检查该值并在满足函数中的条件时显示上面的 div,但它不起作用。例如,即使我输入 2007,也不会显示 div。我究竟做错了什么?
$('#membership-form-personumber').on('keyup change', function(c) {
//initially hide all
if(this.value.length < 4){
$('#alertDiv').hide();
}
else{
switch(parseInt(this.value)){
case 2019: case 2018: case 2017: case 2016: case 2015: $('#alertDiv').show(); break;
case 2014: case 2013: case 2012: case 2011: case 2010: $('#alertDiv').show(); break;
case 2009: case 2008: case 2007: $('#alertDiv').show(); break;
}
}
});
解决方案
更新:希望我现在正确理解了这个问题。在下面的代码片段中添加了一行应该可以解决问题。
default: $('#alertDiv').hide();
在 Firefox 69.0.2 中测试了您的代码,它工作正常。请参阅我的测试页面,我在下面复制并粘贴了您的代码。
您是否检查了浏览器的开发者控制台是否存在阻止脚本正常执行的 Javascript 错误?
当您的 Javascript 已经执行并尝试访问尚不存在的 DOM 节点时,您的页面可能尚未完全加载。您是否将真实代码包装在 document.ready 调用中?见https://learn.jquery.com/using-jquery-core/document-ready/
关于一般代码:是否有任何商业原因为什么在这里使用 switch 语句而不是单个 if 语句检查值是否低于或等于 2005?像这样的东西:
if (parseInt(this.value) < 2005) {
$('#alertDiv').show();
} else {
$('#alertDiv').hide();
}
$('#membership-form-personumber').on('keyup change', function (c) {
//initially hide all
if (this.value.length < 4) {
$('#alertDiv').hide();
}
else {
switch (parseInt(this.value)) {
case 2019: case 2018: case 2017: case 2016: case 2015: $('#alertDiv').show(); break;
case 2014: case 2013: case 2012: case 2011: case 2010: $('#alertDiv').show(); break;
case 2009: case 2008: case 2007: $('#alertDiv').show(); break;
// This line should fix your issue
default: $('#alertDiv').hide();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="alert alert-danger alert-dismissible" style="display: none;" id="alertDiv"> <strong>Note!</strong>
<p>At the moment we cannot accept any players born 05 or earlier beacuse we currently are too many.</p>
</div>
<input id="membership-form-personumber">
</form>
推荐阅读
- c++ - 如何 push_back() 结构的成员变量
- .net - 非管理员的 UserPrincipal.Current.Context 失败
- java - Java Heapspace 错误后会发生 java.util.MissingResourceException 吗?
- regex - awk gsub 正则表达式,匹配单词不在双引号中
- typescript - rxjs 多个可观察开关
- c++ - 为什么这个 C++ 循环不能无限运行?
- sql - 错误 ORA-00907:CREATE TABLE ARTICLE 中缺少右括号
- python - 如何为 iris 包创建 egg/wheel 文件
- windows - 在 Windows Batch 中,为什么用括号括起来的 for 循环不会扩展它被告知要回显的变量?
- python - 从图像中获取 RGB 数据并将其写入具有相应像素的 CSV 文件