【问题标题】:Logic: Combining dropdown boxes to toggle visibility逻辑:组合下拉框来切换可见性
【发布时间】:2013-02-25 02:09:54
【问题描述】:

我有 100 行数据,每行有 3 个属性:年龄、位置、性别。

我有 3 个选择框,用于根据年龄、位置和性别过滤我的数据。

我的函数 setVisible(true) 或 setVisible(false) 使一行隐藏或可见。

我想根据下拉框选择的内容过滤我的数据。

我已经设置了 3 个事件监听器:

$('.age_selector').change(function() {
    for (i=0;i<data.length;i++){
        if (data[i].age == $('.age_selector').val()){
            data[i].setVisible(true);
        } else {
            data[i].setVisible(false);
        }
    }
});
$('.location_selector').change(function() {
    for (i=0;i<data.length;i++){
        if (data[i].location == $('.location_selector').val()){
            data[i].setVisible(true);
        } else {
            data[i].setVisible(false);
        }
    }
});
$('.gender_selector').change(function() {
    for (i=0;i<data.length;i++){
        if (data[i].gender == $('.gender_selector').val()){
            data[i].setVisible(true);
        } else {
            data[i].setVisible(false);
        }
    }
});

我的问题是可见性仅取决于我最近选择的下拉选项。例如,如果我选择美国作为地点,那么我选择男性,我的列表显示所有男性,无论地点/年龄如何。我如何组合逻辑以便将其过滤为仅显示美国男性?

谢谢

编辑: 我希望有一些类似柜台的东西,所以不要有

if (data[i].age == $('.age_selector').val()){
    data[i].setVisible(true);
}

我会有类似的东西

if (data[i].age == $('.age_selector').val()){
    data[i].counter++;
}else{
    data[i].counter--;
}

最后,如果计数器高于某个值,则数据将可见。这可能吗?

【问题讨论】:

    标签: javascript logic toggle visibility


    【解决方案1】:

    我会这样做:

    // Store our current selections
    var age_selection, location_selection, gender_selection;
    
    // Do the real filtering
    function do_filter() {
        // For each element
        for (i=0;i<data.length;i++) {
            // If our data doesn't match one of the selections, set it to not visible
            if (age_selection != null && data[i].age != age_selection) {
                data[i].setVisible(false);
            } else if (location_selection != null && data.location != location_selection) {
                data[i].setVisible(false);
            } else if (gender_selection != null && data.gender != gender_selection) {
                data[i].setVisible(false);
            } else {
                // Otherwise, set it visible
                data[i].setVisible(true);
            }
        }
    }
    
    // When one of the selectors changes, store the selection, and call do_filter
    $('.age_selector').change(function() {
        age_selection = $('.age_selector').val();
        do_filter();
    });
    $('.location_selector').change(function() {
        location_selection = $('.location_selector').val();
        do_filter();
    });
    $('.gender_selector').change(function() {
        gender_selection = $('.gender_selector').val();
        do_filter();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-30
      • 2018-04-05
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多