我是JavaScript新手。我需要通过选择的选项来过滤(显示/隐藏)行(全部-显示所有行,已关闭-隐藏除已关闭,已打开-仅“已打开”行以外的所有选项。)。

我在哪里做错了什么?我想了解。
这是我的代码:

HTML:

<select id="select">
   <option>All</option>
   <option>Closed</option>
   <option>Opened</option>
</select>

<div class="btn">
<input id='status-filter' type="submit" value="Ok"/>
...

<tr class='row' data-row-choice="Opened">
<tr class='row' data-row-choice="Opened">
<tr class='row' data-row-choice="Closed">
...

JS:
$( document ).ready(function() {
    $('.btn').on('click', '#status-filter', function() {
        var selectOption = $('#select option:selected').text();
        $('.row').each(function(selectOption) {
            if ($('.row[data-row-choice]') == 'All') {
                $(this).show();
            } else if ($('.row[data-row-choice]') != selectOption) {
                $(this).hide();
            };
        });
    });
});

编辑:
我误认为``全部''-所有行(``已打开''和``已关闭''),即``所有''包含``已打开''和``已关闭''。我更正了另一个代码。

最佳答案


$( document ).ready(function() {
    $('.btn').on('click', '#status-filter', function() {
        var selectOption = $('#select option:selected').text();

直到这里看起来还可以,假设您的<select>元素具有一个等于"select"的id属性,即<select id="select">...</select>
        $('.row').each(function(selectOption) {

jQuery将使用正在迭代的当前元素的索引填充参数selectOption,例如01等...从函数声明中删除参数。
            if ($('.row[data-row-choice]') == 'All') {

您应该改为检查selectOption的值,因为不会有具有该值的行。
                $(this).show();
            } else if ($('.row[data-row-choice]') != selectOption) {
                $(this).hide();
            };

您遗漏了以前隐藏的项目,现在应该再次显示它们。
        });
    });
});

工作实例
jQuery(function($) {
  $('.btn').on('click', '#status-filter', function() {
    var selectedOption = $('#select').val();

    $('.row')
      .hide()
      .filter(function() {
        return selectedOption == 'All' || $(this).data('row-choice') == selectedOption;
      })
      .show();
  });
});

10-04 22:14
查看更多