首页 > 解决方案 > 如何让 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');
      }
    });
  });
});

标签: jqueryscripting

解决方案


您需要的第一件事是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>,但这应该让你开始


推荐阅读