javascript - 接下来选择与过滤器匹配的选项

标签 javascript jquery jquery-selectors

我在尝试让下拉菜单循环到下一个具有 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。

最佳答案

next 方法仅选择该元素的下一个直接同级元素。如果您向它传递一个过滤器,它只会选择下一个直接兄弟,只有当它与指定的选择器匹配时。直到找到匹配的元素为止它不会继续。另一种方法是 nextAll ,它可以执行此操作,但下一个目标元素不是起始元素的同级元素。您可以从所选元素的父元素开始,然后使用 :has 选择器来查找具有预期子元素的 optgroup,但更好/更高效的选项是:

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 上找到演示。

关于javascript - 接下来选择与过滤器匹配的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37196107/

相关文章:

<a> 的 javascript:void(0) 或 onclick ="return false"- 哪个更好?

jquery - 如何查看使用模板生成的 jquerymobile 源代码?

jquery - .hashchange 不跳转到 anchor 标记?

jQuery:仅在当前类选择器下找不到标签

jquery - 如何在悬停时放大一个 div 并缩小所有其他 div

javascript - 用于导出到 CSV/Excel 的数据 URI(无服务器端请求): browser support/limitations?

javascript - IE 不清除选择值

javascript - Node.js 最高对象值

javascript - jQuery - 即使在动态生成的元素之后,也使元素在 DOM 中最后(在主体关闭之前)

javascript - 在 for 循环中分配点击处理程序