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

Java Spring项目中基于JavaScript实现练习列表点击双向转移的咨询

实现方案

第一步:修正Thymeleaf模板语法错误

你当前的代码有几处明显问题:

  • th:each属性错误绑定到了<ul>标签上,会导致遍历生成多个<ul>而非多个列表项
  • 标签嵌套顺序错误,应该是<li>内部包裹<button>,而非反过来
  • 右侧列表初始状态应该为空,不需要一开始遍历所有练习

修正后的模板代码:

<!-- 左侧候选练习列表 -->
<ul id="leftList" class="exercise-list">
    <li th:each="exercise : ${exercises}" class="exercise-item">
        <button type="button" class="move-btn" th:text="${exercise.name}" th:data-exercise-id="${exercise.id}"></button>
    </li>
</ul>

<!-- 右侧已选练习列表 -->
<ul id="rightList" class="exercise-list">
    <!-- 初始状态为空,选中的项会通过JS动态添加 -->
</ul>

注:给按钮加data-exercise-id属性是为了后续提交表单时可以获取选中的练习ID,不需要的话可以删掉

第二步:编写JavaScript交互逻辑

直接在页面尾部加这段JS即可实现点击移动的效果:

// 给左右两个列表绑定委托事件,不需要给每个按钮单独绑定
document.querySelectorAll('.exercise-list').forEach(list => {
    list.addEventListener('click', e => {
        // 只处理点击了move-btn按钮的情况
        if (e.target.classList.contains('move-btn')) {
            const currentItem = e.target.parentElement;
            const currentList = currentItem.parentElement;
            // 判断当前点击的是左侧还是右侧列表,移动到对面列表
            const targetList = currentList.id === 'leftList' 
                ? document.getElementById('rightList') 
                : document.getElementById('leftList');
            // 移除当前项,添加到目标列表
            currentList.removeChild(currentItem);
            targetList.appendChild(currentItem);
        }
    })
})

可选优化:表单提交处理

如果你需要把选中的练习提交到后端,可以在表单里加一个隐藏的input,提交前收集右侧列表的所有练习ID:

<form th:action="@{/xxx/submit}" method="post" id="exerciseForm">
    <input type="hidden" name="selectedExerciseIds" id="selectedExerciseIds">
    <button type="submit">提交</button>
</form>

对应的JS补充提交逻辑:

document.getElementById('exerciseForm').addEventListener('submit', e => {
    const selectedIds = Array.from(document.querySelectorAll('#rightList .move-btn'))
        .map(btn => btn.dataset.exerciseId)
        .join(',');
    document.getElementById('selectedExerciseIds').value = selectedIds;
})

后端可以直接接收selectedExerciseIds字符串再拆分处理即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:27:02