首页 > 解决方案 > 在当前选择的选项之前获取选择框选项

问题描述

我有一个选择框,将用于一些后端排序。下面我通过将要排序的项目放在中间,然后将当前选择的项目(在此方案中)排序,来直观地表示新订单的外观。

我需要一种方法来获取上一个选项的文本(因此该选项直接位于当前选择的选项之前),以便我可以填充之前的项目文本。我怎样才能做到这一点?

<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>

** 不能假定值是连续的。

标签: jqueryselectdrop-down-menu

解决方案


获取所选选项的索引,从中减去 1,然后使用它来获取上一个选项。

var index = this.selectedIndex;
if (index > 0) {
    var prevOption = $(this).find("option").eq(index-1);
} else {
    prevOption = null;
}

推荐阅读