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

如何在JavaScript中实现表格行间非首列td元素交换(首列td保持固定)

Solution: Swap Non-First TD Elements While Keeping First Column Fixed

Got it, let's adjust your code so that only the columns after the first one swap when clicking the up/down arrows, keeping the first <td> (the position column) locked in place. Here's the step-by-step fix:

Key Change: Modify the moveRowUpDown Function

Instead of moving entire table rows, we'll target and swap only the <td> elements starting from the second one. This preserves the first column's content for each row.

function moveRowUpDown(target){
    // 只响应上下箭头按钮
    if (!target.matches('i.fas.fa-chevron-up, i.fas.fa-chevron-down')) return;

    const currentRow = target.closest('tr');
    let targetRow;

    // 确定要交换的目标行(上一行或下一行)
    if (target.matches('i.fas.fa-chevron-up')) {
        targetRow = currentRow.previousElementSibling;
    } else {
        targetRow = currentRow.nextElementSibling;
    }

    // 如果目标行不存在(比如已经是第一行/最后一行),直接退出
    if (!targetRow) return;

    // 获取当前行和目标行中,除第一个td外的所有单元格
    const currentCells = Array.from(currentRow.querySelectorAll('td')).slice(1);
    const targetCells = Array.from(targetRow.querySelectorAll('td')).slice(1);

    // 逐个交换对应位置单元格的内容
    currentCells.forEach((cell, index) => {
        const tempContent = cell.innerHTML;
        cell.innerHTML = targetCells[index].innerHTML;
        targetCells[index].innerHTML = tempContent;
    });
}

How This Works

  1. Target Valid Buttons: We first check that the clicked element is an up/down arrow to avoid unintended actions.
  2. Find Target Row: Identify the adjacent row (previous for up arrow, next for down arrow) that we need to swap content with.
  3. Select Relevant Cells: Use slice(1) to skip the first <td> in each row, targeting only the columns we want to swap.
  4. Swap Content: Iterate through the selected cells and exchange their inner HTML, keeping the first column untouched.

Full Updated Code

Here's the complete working code including your original HTML and adjusted JavaScript:

HTML

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css">
<div class="col-7 h-100 px-0">
 <select class="form-select mb-3" id="select-session" aria-label="Default select example" onchange="fillAssignTable()">
 <option selected>Select a session from the list</option>
 <option value="1">One</option>
 <option value="2">Two</option>
 <option value="3">Three</option>
 </select>
 <div class="mt-2 mb-3">
 <div class="tableFixHead">
 <table class="table">
 <thead>
 <tr>
 <th class="col-2">Pos</th>
 <th class="col-2">WAB #</th>
 <th class="col-6">Abstract Title</th>
 <th class="text-center col-2">Actions</th>
 </tr>
 </thead>
 <tbody id= "session-table">
 </tbody>
 </table>
 </div>
 </div>
 <div class="d-flex justify-content-end">
 <button class="btn bg-sl-orange text-white px-5" onclick="assignAbstracts()">Assign</button>
 </div>
</div>

JavaScript

var sessionRow;
const sessionTable = document.getElementById('session-table')

async function getAbstractInSession(sessionId){
 let response = await fetch('https://jsonplaceholder.typicode.com/posts');
 let data = await response.json();
 return data
}

function fillAssignTable(){
 let html = "";
 const select_session = document.getElementById("select-session").value;
 getAbstractInSession(select_session).then(abstracts => {
 for(let item in abstracts){
 html += "<tr>"+
 "<td><strong>"+abstracts[item].id+"</strong></td>"+
 "<td><strong>"+abstracts[item].userId+"</strong></td>"+
 "<td>"+abstracts[item].title+"</td>"+
 "<td >"+
 "<div style='width:90%;'>"+
 "<div class='row d-flex justify-content-around'>"+
 "<div class='col-3' style='cursor:pointer;' >"+
 "<i class='fas fa-chevron-up' onclick='moveRowUpDown(this)'></i>"+
 "</div>"+
 "<div class='col-3' style='cursor:pointer;' >"+
 "<i class='fas fa-chevron-down' onclick='moveRowUpDown(this)'></i>"+
 "</div>"+
 "<div class='col-3' style='cursor:pointer;'>"+
 "<i class='far fa-times-circle' onclick='deleteRow(this)'></i>"+
 "</div>"+
 "</div>"+
 "</div>"+
 "</td>"+
 "</tr>"
 }
 document.getElementById("session-table").innerHTML = html;
 });
}

function moveRowUpDown(target){
    if (!target.matches('i.fas.fa-chevron-up, i.fas.fa-chevron-down')) return;

    const currentRow = target.closest('tr');
    let targetRow;

    if (target.matches('i.fas.fa-chevron-up')) {
        targetRow = currentRow.previousElementSibling;
    } else {
        targetRow = currentRow.nextElementSibling;
    }

    if (!targetRow) return;

    const currentCells = Array.from(currentRow.querySelectorAll('td')).slice(1);
    const targetCells = Array.from(targetRow.querySelectorAll('td')).slice(1);

    currentCells.forEach((cell, index) => {
        const tempContent = cell.innerHTML;
        cell.innerHTML = targetCells[index].innerHTML;
        targetCells[index].innerHTML = tempContent;
    });
}

// 保留原有的删除行函数(如果需要)
function deleteRow(target){
    const row = target.closest('tr');
    row.remove();
}

// 占位的assignAbstracts函数
function assignAbstracts(){
    // 这里可以添加你的分配逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:12:47