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

如何修复JS实现的CRUD中更新功能新增而非更新的问题

解决CRUD编辑功能点击Add按钮新增而非更新的问题

问题根源是你没有标记当前正在编辑的条目索引——点击编辑按钮后只是把数据填充到输入框,但addMovie函数始终执行新增操作。按以下步骤修改即可解决:

  • 新增变量存储编辑索引,初始值设为-1(表示非编辑状态):

    let editIndex = -1;
    
  • 修改update函数,记录当前编辑的索引,同时把按钮文字改成"Update",明确当前状态:

    function update(i){
        editIndex = i;
        movieName.value=movieContainer[i].name
        movieYear.value=movieContainer[i].year
        movieGenre.value=movieContainer[i].genre
        addBtn.textContent = "Update";
    }
    
  • 重写addMovie函数,判断当前是新增模式还是更新模式:

    function addMovie(){
        let movie = {
            name:movieName.value,
            year:movieYear.value,
            genre:movieGenre.value,
        }
    
        if(editIndex === -1){
            // 新增模式:添加新数据
            movieContainer.push(movie)
        }else{
            // 更新模式:替换对应索引的旧数据
            movieContainer.splice(editIndex, 1, movie);
            // 重置编辑状态
            editIndex = -1;
            addBtn.textContent = "Add";
        }
        localStorage.setItem('movie',JSON.stringify(movieContainer))
        display()
        clearMovie()
    }
    
  • 补充clearMovie函数,清空输入框时同步重置编辑状态:

    function clearMovie(){
        movieName.value=''
        movieYear.value=''
        movieGenre.value=''
        // 清空时恢复新增模式
        if(editIndex !== -1){
            editIndex = -1;
            addBtn.textContent = "Add";
        }
    }
    

修改后,点击编辑按钮时按钮会切换为"Update",此时点击按钮就会更新对应行的数据;完成更新或手动清空输入框后,按钮会变回"Add",回到新增模式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 02:35:55