当用户单击按钮时从数组中删除对象

Posted

技术标签:

【中文标题】当用户单击按钮时从数组中删除对象【英文标题】:remove object from array when user clicks button 【发布时间】:2021-09-19 19:12:06 【问题描述】:

我正在尝试将用户选择的项目存储到一个对象中,这样当用户单击“删除按钮”时,它也会从我的对象中删除该项目。我似乎遇到了一个错误,其中只有我的数组中的第一个对象将被删除,没有别的。我可以帮忙吗?

每个 li 的 data-id 值为 i,其中 i 是一个整数,用户添加到列表中的每个项目都会递增一次,例如: 用户点击添加

数据ID:1

用户点击添加

数据ID:2

等等等等,目前当用户点击remove...它只会删除id:0的对象。但是点击列表中的任何其他项目都不会影响executiveDataArr

编辑:包括我的 html 文件,这是一个 Python Flask 应用程序,我使用 Jinja 模板以及 Wtforms 生成表单,因为我有一个动态选择字段,它使用我的数据库从该数据库中提取练习名称用户从中挑选来构建例程。

createRoutine.html

% extends 'profileSignedInBase.html' %

% block content %
<div>
  <div id="media">
    <div>
      <form action="/workoutroutines">
        form.hidden_tag()


        % for field in form if field.widget.input_type != 'hidden' %

         field(placeholder=field.label.text) 
        % endfor %


        <button id="createBtn">CREATE</button>
      </form>

      <div>

        <button id="addBtn">Add Exercise To List</button>
      </div>


      <h1>This is what you have planned for your routine</h1>
      <ol id="routineWishlist">

      </ol>
    </div>
  </div>
  <script src="/static/addExercise.js"></script>
  % endblock %

addExercise.JS

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

// generate list of items the user has selected for their workout
    document.querySelector("#media").addEventListener("click", function (e) 

//Add Item to 
  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)      //"name": "workout 1","description": "My favorites"
    console.log(exerciseDataArr) //After adding 2 exercises to the list "exercise": "2 Handed Kettlebell Swing","id": 0"exercise": "2 Handed Kettlebell Swing","id": 1


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

  
  if (e.target.id === "removeBtn") 
    e.preventDefault();


    
    exerciseName = $(e.target).closest('div').attr('id');
    exerciseOrder = parseInt($(e.target).closest('li').attr('data-id'));
    console.log("remove " + typeof(exerciseOrder) + " " + exerciseOrder + " at " + exerciseName )
    console.log("inside " + typeof(exerciseDataArr)) //object
    //remove from displayed list of exercises
    $(e.target).closest('div').remove()

    // remove from object
    for(let val in exerciseDataArr)
      val = parseInt(val)
      console.log(`id: $val`)
      // if the exerciseDataArr contains id: exerciseOrder delete from exerciseDataArr
      if(exerciseDataArr.hasOwnProperty("id") == exerciseOrder   )// <---does not activate unless the first 'li' is clicked. 
        console.log("the object has been found, now delete it")
        delete exerciseDataArr[exerciseOrder]
        val = undefined;
      
    
    console.log(exerciseDataArr)

  

【问题讨论】:

【参考方案1】:

您可以发布更多代码吗?如果可能也发布 HTML 以及代码中的 exerciseDataArr 是什么,没有明确解释

【讨论】:

并为 exerciseDataArr 和 exerciseOrder 添加您的日志输出 添加了一些修改。如果需要,我也可以包含此存储库以查看原始文件

以上是关于当用户单击按钮时从数组中删除对象的主要内容,如果未能解决你的问题,请参考以下文章

如何在关闭浏览器时从数据库中删除数据

MVC 问题在按钮单击时从 JSon 对象填充 JQuery DataTable

单击事件后如何从 ReactJS 中的数组中删除对象

单击时从循环中禁用按钮

取消选中复选框时从收音机中删除“选中”

更改密码时从所有浏览器中注销用户