使用 jQuery 从所选选项中选择前一个元素
我想访问所选选项的前一个选项的值,即距所选选项 2 的值。 (抱歉,很难表达它!)
例如,如果从此处选择“4”,我想获取选项“2”的值。
<option value ="1">1</option>
<option value ="2">2</option>
<option value ="3">3</option>
<option value ="4">4</option>
我知道前一个方法有 prev 方法,但是其他方法呢?
谢谢!
I want to access the value of the select option that one before the previous one of the selected one, meaning 2 away from the selected one. (sorry, it's hard to phrase it!)
For instance, if "4" is selected from here, I want to get the value of the option "2".
<option value ="1">1</option>
<option value ="2">2</option>
<option value ="3">3</option>
<option value ="4">4</option>
I know there is prev method for the immediately previous one, but how about the other ones?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以执行此
示例: http://jsfiddle.net/jasongennaro/NcPgV/
但是,这会返回当选择为 2 或更低时,什么也没有。
You could do this
Example: http://jsfiddle.net/jasongennaro/NcPgV/
However, this returns nothing when the selection is 2 or lower.
正如其他人所说,您可以调用 prev() 两次。
另一种更具可扩展性的解决方案是使用 prevAll()。它返回从最近的兄弟向外排序的元素,因此您可以将其与 eq() 组合:
这样,如果您想从所选选项中移走 2 个以上的选项,则无需对
prev()
进行多次调用。As others have said, you can call prev() twice.
An alternative, more scalable solution is to use prevAll(). It returns elements ordered from the closest sibling outwards, so you can combine it with eq():
This way, you won't have to chain multiple calls to
prev()
if you want to move more than 2 options away from the selected one.prev 函数将获取给定节点的前一个兄弟节点;调用两次就可以达到你想要的效果。
这是小提琴
The prev function will get the preceding sibling for a given node; calling it twice will accomplish what you want.
Here's the fiddle