javascript - 防止重复函数onchange事件jQuery
问题描述
我在下面有这个片段
$(document).ready(function(){
$("#selectTest").change(function(e){
if($(this).val() == "01"){
$(".show").hide();
}else{
$(".show").show();
};
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="show">
Sample Text
</div>
<select name="test" id="selectTest">
<option value="00"></option>
<option value="01">Click this to hide text</option>
<option value="02">Click this to show text</option>
</select>
</body>
</html>
上面的片段看起来不错,但是当页面加载时从第一个选择的选项时我遇到了麻烦。我必须单击不同的按钮才能使该hide
功能起作用。我通过在我的代码中添加 解决了这个问题,if ... else
以便在页面加载时隐藏功能将正常运行。
$(document).ready(function(){
$("#selectTest").change(function(e){
if($(this).val() == "01"){
$(".show").hide();
}else{
$(".show").show();
};
})
if($("#selectTest").val() == "01"){
$(".show").hide();
}else{
$(".show").show();
};
})
上面的代码看起来不合适,因为我必须重复我所做的功能,有没有更好的方法来解决这个问题?
解决方案
您可以使用 jQuery触发事件(更改) ,而不是编写两次代码.trigger()
:
$("#selectTest").trigger('change');
工作代码示例:
$(document).ready(function(){
$("#selectTest").change(function(e){
if($(this).val() == "01"){
$(".show").hide();
}else{
$(".show").show();
};
});
$("#selectTest").trigger('change');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="show">
Sample Text
</div>
<select name="test" id="selectTest">
<option value="00"></option>
<option value="01">Click this to hide text</option>
<option value="02">Click this to show text</option>
</select>
推荐阅读
- javascript - 我正在创建一个聊天应用程序并尝试实现类似于 twitch 表情的自定义表情。我在正确的道路上吗?
- c# - 无论如何要检测是否运行了文件/可执行文件?
- python - Python 警告 - 找不到命令
- ruby - 得到
通过 sendgrid 提交联系表时 - python - 如何跳过 python 列表字段
- ios - 开发2012年Objective C开发的iphone版ipad app
- python - 使用赋值运算符“=”时的 SettingWithCopyWarning
- php - 在几行php中提取bbcode属性
- laravel - count() 使用后返回 0 跳过并取入 laravel ORM
- apache-spark - 强制删除 spark pod 驱动程序时,驱动程序不会重新启动