jQuery,选择最近的兄弟与属性(下一个或上一个) [英] jQuery, select nearest sibling with attribute (next or previous)

查看:120
本文介绍了jQuery,选择最近的兄弟与属性(下一个或上一个)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于下面标记的选择下拉列表。

I have a select dropdown similar to the markup below.

<select class="myselect" name="myname">
  <option value="0" disabled="disabled">0</option>
  <option value="1" disabled="disabled">1</option>
  <option value="2" disabled="disabled">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7" selected="selected" disabled="disabled">7</option>
</select>

我正在试图弄清楚如何使用jQuery来选择最近的启用兄弟选中元素。在上面的例子中,我想选择选项6.我意识到我可以使用.prev(),但这只会上升。有时用户选择的数字较小,我需要选择next()选项。

I'm trying to figure out how to use jQuery to select the closest "enabled" sibling to the "selected" element. In the above example, I would like to select option 6. I realize that I can user .prev(), but that only goes up. Sometimes the user has a lower number selected and I need to select the next() option.

感谢您的帮助!

推荐答案

一个选项是使用 nextAll prevAll 方法,您可以检查所选元素的长度,如果下一个未禁用元素存在选择该元素,否则选择最接近的未禁用元素。

One option is using nextAll or prevAll method, you can check the length of the selected element, if the next not disabled element exists select that element otherwise select the closest previous not disabled element.

var $o = $('.myselect option'),
    $s = $o.filter(':selected'),
    $next = $s.nextAll(':not(:disabled)').first();

if ($next.length) $next.foo();
else $s.prevAll(':not(:disabled)').first().bar();

http://jsfiddle.net/DsWh6/

这篇关于jQuery,选择最近的兄弟与属性(下一个或上一个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆