下一个选择匹配过滤器的选项

Posted

技术标签:

【中文标题】下一个选择匹配过滤器的选项【英文标题】:Next select option that matches filter 【发布时间】:2016-05-12 19:43:24 【问题描述】:

我在尝试让下拉菜单循环到具有 data-completed=false 的下一个选项时遇到问题

<select id="selectionChamp">
<optgroup label="1">
  <option data-completed=true selected>Text 1</option>
</optgroup>
<optgroup label="2">
  <option data-completed=true>Text 2</option>
</optgroup>
<optgroup label="3">
  <option data-completed=true>Text 3</option>
</optgroup>
<optgroup label="45">
  <option data-completed=false>Text 4</option>
  <option data-completed=false>Text 5</option>
</optgroup>
</select>

<input type="button" id="fieldNext" value="Next">

javascript

    $("#fieldNext").click(function() 
    var $selected = $("option:selected");
    var filter = "[data-completed!=true]";
    $selected.attr("data-completed", true).prop("selected", false);
    var $next = $selected.next("option"+ filter);
    if ($next.length === 0) 
      $next = $selected.parent("optgroup").next("optgroup:has(option"+ filter+")").find("option"+ filter+":first");
    
    $next.prop("selected", true);
);

见:http://jsfiddle.net/w9kcd/105/

我知道它在filter = ""; 时有效,但在filter = "[data-completed!=true]"; 时无效

它应该从 1 开始,然后到 4,然后是 5,跳过 2 和 3。

【问题讨论】:

【参考方案1】:

next 方法只选择元素的下一个直接兄弟。如果您将过滤器传递给它,它将选择下一个直接兄弟,只有当它匹配指定的选择器时。在找到匹配元素之前它不会去。另一种方法是nextAll,它执行此操作,但下一个目标元素不是起始元素的兄弟。您可以从所选元素的父级开始,然后使用:has 选择器来查找具有预期子级的optgroups,但更好/更有效的选择是:

var $options = $("#selectionChamp option");

$("#fieldNext").click(function() 
    var $selected = $("option:selected").attr("data-completed", 'true');
    // get the index of the current selected element
    var i = $options.index($selected);  
    // find the first next matching element
    // you can also pass a string to the filter method: `[data-completed!="true"]`
    var $next = $options.slice(i /* + 1 */).filter(function() 
        return this.getAttribute('data-completed') !== "true"; 
    ).eq(0).prop("selected", true);
);

Here你可以在 jsfiddle.net 上找到一个演示。

【讨论】:

以上是关于下一个选择匹配过滤器的选项的主要内容,如果未能解决你的问题,请参考以下文章

Drupal 查看具有近似匹配的暴露过滤器

选择后多选上升

Ansible 列表变量和选择过滤器以忽略匹配项

如何选择与过滤器匹配的连续元素

jquery过滤器搜索应根据文本选择匹配的DIV

wireshark使用教程