You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript行排序及上下箭头显示异常问题求助

问题分析

你的代码里第一个.line元素是仅包含标签的行,它没有排序箭头,但updateIconsVisibility函数会遍历所有.line元素,导致:

  • 这个空标签行被当作第0行(但它没有箭头,所以无实际效果)
  • 真正的第一行数据行变成了index=1,因此会同时显示UP和DOWN图标
  • 最后一行数据行是index=3(总共有4个.line),所以只显示UP图标

另外,移动行之后,data-index属性和表单元素的name属性里的索引没有更新,后续点击移动按钮会出现逻辑错误。

修复方案

1. 调整HTML结构

移除仅含标签的行的.line类,避免它被纳入排序行的统计:

<div style="margin-top: 15px;display: flex;min-width: 329px;">
    <div style="float:left;display: flex; flex-direction: column;width: 10%;">
        <label for="select-group" class="form-label">Select Status</label>
    </div>
</div>

2. 更新JavaScript逻辑

新增updateRowIndices函数,在移动行后同步更新所有数据行的data-index以及表单元素的name属性,确保索引与当前顺序一致:

$(document).ready(function () {

  // 更新所有行的索引和表单name属性
  function updateRowIndices() {
    $('.line').each(function(index) {
      // 更新按钮的data-index
      $(this).find('.move-up-button, .move-down-button').data('index', index);
      // 更新select的name
      $(this).find('select[name^="status["]').attr('name', `status[${index}]`);
      // 更新input的name
      $(this).find('input[name^="status-input["]').attr('name', `status-input[${index}]`);
    });
    updateIconsVisibility();
  }

  function moveUp(index) {
    if (index === 0) return;
    var $currentItem = $('.line').eq(index);
    var $prevItem = $('.line').eq(index - 1);
    $currentItem.insertBefore($prevItem);
    updateRowIndices();
  }

  function moveDown(index) {
    var totalRows = $('.line').length;
    if (index === totalRows - 1) return;
    var $currentItem = $('.line').eq(index);
    var $nextItem = $('.line').eq(index + 1);
    $currentItem.insertAfter($nextItem);
    updateRowIndices();
  }

  function updateIconsVisibility() {
    var totalRows = $('.line').length;
    $('.line').each(function (index) {
      var $upIcon = $(this).find('.fa-chevron-circle-up');
      var $downIcon = $(this).find('.fa-chevron-circle-down');

      if (index === 0) {
        $upIcon.hide();
        $downIcon.show();
      } else if (index === totalRows - 1) {
        $upIcon.show();
        $downIcon.hide();
      } else {
        $upIcon.show();
        $downIcon.show();
      }
    });
  }

  $(document).on('click', '.move-up-button', function() {
    var index = $(this).data('index');
    moveUp(index);
  });

  $(document).on('click', '.move-down-button', function() {
    var index = $(this).data('index');
    moveDown(index);
  });

  updateIconsVisibility();
});

修复后的效果

  • 首行数据行仅显示DOWN图标
  • 末行数据行仅显示UP图标
  • 中间行同时显示两个图标
  • 移动行后,所有行的索引和表单属性会同步更新,后续移动操作正常

内容的提问来源于stack exchange,提问作者Jake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 13:03:32