代码之家  ›  专栏  ›  技术社区  ›  Alex

在当前选定选项之前获取“选择框”选项

  •  0
  • Alex  · 技术社区  · 7 年前

    我有一个选择框,将用于一些后端排序。下面,我通过将要排序的项放在中间,然后将当前选定的项(在此方案中)放在后面,给出新顺序的可视化表示。

    我需要一种方法来获取前一个选项的文本(因此该选项直接位于当前选定选项之前),这样我就可以填充前一个项的文本。我该怎么做?

    <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 回复  |  直到 7 年前
        1
  •  0
  •   Barmar    7 年前

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

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