Jquery过滤器根据先前选择组的选择选择下一个组

时间:2015-07-09 17:51:52

标签: jquery

所以我需要用户选择三个选择框(所有多选)。

这个想法是有许多不同的特定类型的甜点,而不是有一个巨大的多选框,我包括两个其他多选框,以缩小用户必须点击的内容。

在这种情况下,他们首先浏览“layer1”,单击Cookie,然后第二层应该只显示Sprinkled Cookie和Iced Cookie。

然后,在“layer2”上,如果他们同时选择Sprinkled Cookie和Iced Cookie,那么Dark Sprinkled Cookie和White Sprinkled Cookie以及White Iced Cookie应该显示在“layer3”上。

我无法弄清楚如何进行过滤并用正确的结果替换html文本。

<select id="layer1" multiple="multiple">
  <option my_id=3>Chocolate</option>
  <option my_id=5>Cookie</option>
</select>

<select id="layer2" multiple="multiple">
  <option parent_id=3 my_id=6>Milk Chocolate</option>
  <option parent_id=5 my_id =7>Sprinkled Cookie</option>
  <option parent_id=5 my_id =8>Iced Cookie</option>
</select>

<select id="layer3" multiple="multiple">
  <option parent_id=7 my_id=10 >Dark Sprinked Cookie</option>
  <option parent_id=7 my_id=11 > White Sprinkled Cookie</option>
  <option parent_id=8 my_id=12> White Iced Cookie </option>
</select>
<script>
$( "select" )
  .change(function () {
    console.log($(this).attr('id')); //tells me the layer i think
    nextlayerstuff = //get the next layer somehow 
    options = $(nextstuff).filter(not sure what to do here).html()
    //somehow display the new select options for the next layer
</script>

1 个答案:

答案 0 :(得分:1)

一个有趣的场景。几个指针:您需要先缓存所有值,然后您需要相应地添加或删除它们。您可能应该关联父选择和子选择(而不是仅依赖关联的父选项和子选项)。将这些ID移动到数据属性而不是自定义属性也可能不是一个坏主意。我已经整理了一个可能适用于您的目的的演示。代码或多或少地完整记录。

WARNING:Xst:653 - Signal <GND_3_o> is used but never assigned. This sourceless signal will be automatically connected to value GND.
WARNING:Xst:653 - Signal <PWR_3_o> is used but never assigned. This sourceless signal will be automatically connected to value GND.
$("select").each(function(){
    // cache all options
    $(this).data('options', $('option', this));
}).on('change', function(e){
    var current = this, selected = [];
    
    // find all selected for the current select and
    // store them in a local variable
    $('option:selected', current).each(function(){
        selected.push($(this).data('id'));
    });
    
    // find all selects that depend on this one.
    $("select").filter(function(){
        return $(this).data('depends-on') === current.id;
    }).each(function(){
        // search our cached options and filter them
        // by the selected option(s).  Store them in
        // a local variable.
        var children = $(this).data('options').filter(function(){
            return selected.indexOf($(this).data('parent')) > -1;
        });
        
        // empty and repopulate the select with the
        // filtered results. Also, trigger the next
        // select so the effect cascades.
        $(this).empty().append(children).trigger('change');
    });
}).trigger('change'); // trigger change so it filters
                      // on page load.