jquery - 在当前选择的选项之前获取选择框选项
问题描述
我有一个选择框,将用于一些后端排序。下面我通过将要排序的项目放在中间,然后将当前选择的项目(在此方案中)排序,来直观地表示新订单的外观。
我需要一种方法来获取上一个选项的文本(因此该选项直接位于当前选择的选项之前),以便我可以填充之前的项目文本。我怎样才能做到这一点?
<p>Select an item in the following list that you want this item to go <i>before</i>.</p>
<select name="order-list" id="order-list" class="form-control">
{array_to_select($list)}
</select>
<p class="m-t-md">Presentation order after changes:</p>
<ul class="list-group">
<li class="list-group-item" id="sortable-item-before">Before Item</li>
<li class="list-group-item" id="sortable-item-current">{$current_item}</li>
<li class="list-group-item" id="sortable-item-after">After Item</li>
</ul>
<script>
$(document).ready(function () {
var before = $('#sortable-item-before');
var after = $('#sortable-item-after');
$('#order-list').on('change', function (e) {
e.preventDefault();
after.html($(this).find('option:selected').text());
});
});
</script>
示例列表选项:
<option value="68">Some option</option>
** 不能假定值是连续的。
解决方案
获取所选选项的索引,从中减去 1,然后使用它来获取上一个选项。
var index = this.selectedIndex;
if (index > 0) {
var prevOption = $(this).find("option").eq(index-1);
} else {
prevOption = null;
}
推荐阅读
- docker - Google Container Registry 意外 HTTP 状态:504 网关超时
- android - WakeLock 在现代 Android 中的用途?
- javascript - 使用 JavaScript 使用 for 循环在数组中搜索
- java - 使用单独的应用程序处理文件修改的任何标准技术?
- ios - Swift URL.path 更改 utf-8 字符的编码
- wordpress - WordPress - 如何找到与当前自定义帖子类型存档页面匹配的 slug 页面?
- html - 如果按钮在组件 A 中且元素在组件 B 中,则单击时显示元素
- javascript - 在 React 中添加 onClick 到提交按钮
- python - 带有 MySQL 8 服务器的 MySQL 实用程序
- iphone - 如果用户名和密码都为空,如何显示警报消息