javascript - 在 ('change' 上)功能不起作用

标签 javascript jquery sorting filter

所以我想做的是根据用户选择的“类别”更新“主题”选择。我想要做的是监视 ID 为“category-filter”的元素上属性“data-curr_filter”的更改事件。我的每个类别的 jQuery 都通过 web-inspector 进行了测试,所以我相信它与函数的 .on('change') 部分有关(它不会触发控制台。日志)。其代码如下:

搜索过滤器的 HTML:

<span id="category-filter" class="filter-select" data-target="filter_categories" data-curr_filter="all">
  All Categories &nbsp; <i class="fa fa-angle-down"></i></span>
filter by
<span class="filter-select" data-target="filter_topics">
  All Topics &nbsp; <i class="fa fa-angle-down"></i>
</span>

“主题”的 HTML:

<ul class="filter-list" id="filter_topics" aria-labelledby="filter_topics">
    <li data-val="affordability" data-cat="communities">Affordability</li>
    <li data-val="market_conditions" data-cat="communities">Market Conditions</li>

jQuery:

$(document).ready(function() {
  console.log("Hello Moto");
  $(document).on('change', '#category-filter', function() {

  console.log("Something change");

  if ($('#category-filter').attr('data-curr_filter') == 'all' ){
    $('#filter_topics li').show();
  }  

  if ($('#category-filter').attr('data-curr_filter') == 'communities'){
    //show all topics as a "blank slate" before altering the display elements according category
    $('#filter_topics li').show();
    //hide all the elements
    $('#filter_topics li').toggle();
    //show only the topics labeled with communities
    $('#filter_topics li[data-cat=communities').toggle();    
  } 
  ...

最佳答案

答案:

只是做一个 onclick 工作...有点生气我完全忽略了这一点。

 $(document).on('click', '#filter_categories li', function() {
    var selectedCategory = $(this).attr('data-val');

    if (selectedCategory == 'all' ){
      $('#filter_topics li').show();
    }

    if (selectedCategory == 'communities'){
        //show all topics as a "blank slate" before altering the display elements according category
        $('#filter_topics li').show();
        //hide all the elements
        $('#filter_topics li').toggle();
        //show only the topics labeled with communities
        $('#filter_topics li[data-cat=communities').toggle();    
      }
...

TL;DR 根据我的问题:

因为它是<span>而不是<input> , <select><textarea>元素,它没有 .on('change') 事件观察器。如果我找到答案,我会将其发布在这里。

关于javascript - 在 ('change' 上)功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35562250/

相关文章:

javascript - jQuery DataTables - 访问所有行数据

sorting - 用于对表进行排序的 Google Sheets 脚本给出错误 "Cell reference out of range"

java - 随机化方法的问题

google-maps - 使用 for 循环将标记聚类器添加到谷歌地图?

javascript - 与手动设置单元格宽度不一致

javascript - 如何动态注册到jquery自定义事件?

javascript - 当我悬停在 li 上时如何更改 div

c++ - SPOJ : GENERAL (Time limit exceeded)

javascript - AJAX DJango 从多个文件字段中获取文件

javascript - 如何在不重复代码的情况下对多个 div 使用相同的 jQuery 函数