jquery - 如何让 jquery 脚本在下拉菜单事件中触发?
问题描述
对于过滤器搜索,我使用表单来显示下拉菜单,并且我需要根据从菜单中选择的选项的值向父 div 添加或删除一个类。
这个脚本至少有两个问题: 1. 它是与页面一起加载并立即添加类。只有当用户选择一个选项时,我才需要它运行。2. 选择选项不会更新页面。3. 另外我不确定我的变量 $key 是否存储了正确的值。我想要从选项中选择的值。
我查看了几个类似的问题,并查看了 .select()、.change() 和 .trigger() 的 jquery 文档,但我还没有将适合我的情况的组合放在一起。
下面是我正在使用的精简基本脚本,它有效地将类添加到示例 HTML。
<select name="SelectBox-ByDestination" id="SelectBox-ByDestination">
<option value="" disabled selected hidden>Select a Destination...</option>
<option value="Argentina">Argentina</option>
<option value="Australia">Australia</option>
<option value="Iceland">Iceland</option>
</select>
<div class="Item">
<h3>Program</h3>
<div class="destination">
<h4>Destinations</h4>
<ul>
<li>Iceland</li>
</ul>
</div>
</div>
$(function () {
$('#SelectBox-ByDestination').change(function() {
var $dest = $(this).val();
$('.destinations').each(function() {
var $matches = $('.destination li').filter(function() {
return $(this).text() === $dest
});
if (!$matches.length) {
$(this).parent().addClass('hideByDestinationDropDownMenu');
} else {
$(this).parent().removeClass('hideByDestinationDropDownMenu');
}
});
});
});
解决方案
您需要的第一件事是change
在<select>
然后你想在事件触发时将它value
与单个元素中的文本进行比较<li>
$('#SelectBox-ByDestination').on('change', function() {
var dest = $(this).val();
$('.destinations').each(function() {
// filter matching `<li>`
var $matches = $('.destintion li').filter(function() {
return $(this).text() === dest// or use `includes() for partial matches
});
if(!$matches.length){
// hide this destination div
}else{
// show it
}
});
});
我猜你也想隐藏其他<li>
,但这应该让你开始
推荐阅读
- javascript - 如果滑动分别在开始或结束时如何隐藏箭头
- zend-framework3 - 使用 Zend 进行文件访问的类推荐
- python - 如何解决 Tensorflow CNN 模型的“TypeError:__array__() 需要 1 个位置参数但给出了 2 个”?
- algorithm - 二叉树 - 从最后一层遍历到根的最优雅的方式
- mongodb - 如何在 mongoDB 中正确索引三个属性?
- mysql - 在查询执行期间丢失连接
- zip - 密码保护bash中的压缩目录
- r - 在每个 ID 有多个观察值的 df 中,如何根据另一个变量有条件地查找日期?
- java - 在 com.example.accountproject.models.interfaces.MemberSv 定义中创建名称为“memberSv”的 bean 时出错
- dependency-injection - 如何使用匕首提供列表适配器类的依赖关系?- 当适配器类将接口作为参数时