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

Flask项目中点击移除按钮仅能删除数组首个对象的问题求助

Fixing the "Only First Item Deletes" Issue in Your Workout Routine Builder

Hey there! I see exactly what's going wrong with your delete functionality—let's break it down and fix it.

The Problem in Your Current Code

In your removeBtn click handler, this line is the root cause of the issue:

if(exerciseDataArr.hasOwnProperty("id") == exerciseOrder ){

You're checking if the array itself has an id property matching exerciseOrder, not if any of the objects inside the array have that id. That's why only the first item seems to work accidentally, while all others do nothing.

The Fixed JavaScript Code

Here's the corrected version of your addExercise.js with proper delete logic:

let jsonData = {} 
let exerciseDataArr = [] 
let i = 0; 

document.querySelector("#media").addEventListener("click", function (e) { 
    // Add Item logic (unchanged from your original code)
    if (e.target.id == "addBtn") { 
        e.preventDefault(); 
        var exerciseValue = $('#exerciseChoices').find(":selected").text(); 
        var workoutName = $('#workoutName').val(); 
        var workoutDescription = $('#description').val(); 

        if (workoutName == "") { 
            console.log("please fill out all data") 
            alert("please add a name") 
            return; 
        } 
        if (workoutDescription == "") { 
            console.log("please fill out all data") 
            alert("please add a description") 
            return; 
        } 

        console.log("You clicked on the Add button") 
        var li = document.createElement("li"); 
        var div = document.createElement("div") 
        var remove = document.createElement("button"); 

        li.setAttribute("data-id", i) 
        div.setAttribute("id", `exercise${i}`) 
        remove.setAttribute("id", "removeBtn"); 
        remove.innerText = 'Remove'; 

        try { 
            jsonData['name'] = workoutName; 
            jsonData['description'] = workoutDescription; 
            exerciseDataArr.push({ 'exercise': exerciseValue, id: i}) 
        } catch (error) { 
            console.error(error) 
        } 
        i++; 

        console.log(jsonData) 
        console.log(exerciseDataArr) 

        var t = document.createTextNode(exerciseValue); 
        div.append(li) 
        li.append(remove); 
        li.appendChild(t); 
        document.querySelector("#routineWishlist").appendChild(div); 
    } 

    // Fixed Remove Item logic
    if (e.target.id === "removeBtn") { 
        e.preventDefault(); 
        exerciseOrder = parseInt($(e.target).closest('li').attr('data-id')); 
        console.log("remove " + typeof(exerciseOrder) + " " + exerciseOrder) 

        // Remove from displayed list
        $(e.target).closest('div').remove() 

        // Find the index of the object with matching id in the array
        const indexToRemove = exerciseDataArr.findIndex(item => item.id === exerciseOrder);
        if (indexToRemove !== -1) {
            // Delete the element at that index
            exerciseDataArr.splice(indexToRemove, 1);
            console.log("The object has been found and deleted!")
        }

        console.log(exerciseDataArr) 
    }
});

What Changed & Why

  1. Removed the incorrect hasOwnProperty check: Instead, we use findIndex() to locate the position of the object in the array where item.id matches exerciseOrder.
  2. Used splice() to delete the element: Once we have the correct index, splice(indexToRemove, 1) removes that single element from the array. This is better than delete because delete leaves an empty slot in the array, while splice properly reindexes the array.
  3. Cleaned up redundant variables: We removed exerciseName since it wasn't needed for the delete logic.

Bonus Alternative Approach

If you prefer a functional programming style (without mutating the original array), you can replace the splice line with:

exerciseDataArr = exerciseDataArr.filter(item => item.id !== exerciseOrder);

This creates a new array with all items except the one we want to delete, which can be safer in some use cases.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:42:42