【问题标题】:How to remove an object from an array using click events如何使用单击事件从数组中删除对象
【发布时间】:2020-02-03 00:14:32
【问题描述】:

我是 javascript 新手,需要一些帮助。我整个星期都在尝试查找这个,但似乎无法理解这个概念。我编写了一些代码,允许我使用innerhtml() 创建卡片。这些卡片从数组中获取所有必要的信息。一旦单击所述卡片上的按钮,我已经到达将删除卡片的位置,但是它会删除所有卡片,并且我需要它在单击按钮时单独删除卡片..原谅我的术语和缺乏理解。这是我的 javascript 代码。

console.log("HelloWorld!");
//print to dom function for innerhtml
const printToDom = (divId, textToPrint) => {
    console.log(textToPrint);
    const selectedDiv = document.getElementById(divId);
    selectedDiv.innerHTML = textToPrint
};

//this is my hogwarts array

const hogwartsHouse = [
    'Griffindor', 'Hufflepuff', 'Slytherin', 'Ravenclaw' 
];

//this variable grabs the users input into my form

const names = document.getElementById("insertName");

//this variable sets the student id to 0
//student id is located inside the sort init function

let studentId = 0;


const students = [];

//this function allows my form to be seen

function openForm() {
   x = document.getElementById("form");
   if(x.style.display === "none") {
       x.style.display = "block";
   } else {
       x.style.display = "none";
   }
};

//this function builds the card

const sortBuilder = (sortingHat) => {
    
    let domString = '';
    for(let i = 0; i < sortingHat.length; i++){
        domString +=    `<div id="cardContainer">`
        domString +=    `<div class="card" style="width: 18rem;">`
        domString +=        `<div class="card-body">`
        domString +=        `<h5 class="cardTitle">${sortingHat[i].name}</h5>`
        domString +=        `<p class="card-text">${sortingHat[i].house}</p>`
        domString +=        `<a onclick="expelStudentEvent()" id="${sortingHat[i].id}" href="#" class="expel">Expel</a>`
        domString +=        `</div>`
        domString +=    `</div>`
        domString +=    `</div>`
    }
    
    printToDom('studentCard', domString)
    
};



//pass in id of the card i'm clicking

//i want this function to delete 1 card when the button on said card is clicked

const expelStudentEvent = () => {
    let domString = '';
    for(let i = 0; i < students.length; i++){
        domString += ``
        } if(students.length = 0){}
        console.log(students)
    printToDom('studentCard', domString);
};


//this function takes my users input into the form and my hogwarts array into an array that gives each input an id

const sortInit = (e) => {

    const student = {
        id: studentId,
        name: names.value,
        house: hogwartsHouse[Math.floor(Math.random() * hogwartsHouse.length)],
    }
    students.push(student);
    console.log(students);
    studentId++;
    sortBuilder(students);
};

// const removeCard = () => {
//     let myCard = document.getElementById(e.target.id);
// }

//this function holds my event listeners

const events = () =>{
    document.getElementById('sort').addEventListener('click', sortInit)
    document.getElementById(e.target.id).addEventListener('click', expelStudentEvent)
}

//this function holds all of the previous functions

const init = () => {
    openForm();
    sortBuilder(students);
    events(students)
    expelStudentEvent(e)
    sortInit(expelStudentEvent)
};

//this function executes all functions

init();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="main.css">
</head>

<body>
    <div id="jumbo" class="jumbotron">
        <h1 class="display-4">Sorting Hat</h1>
        <p class="lead">Hello muggles, are you a big fan of Harry Potter? </p>
        <hr class="my-4">
        <p>Well you are in luck. Now you will be able to use this website to try on the sorting hat and see which house you will be sorted into.</p>
        <p class="lead">
          <a id="initForm" class="btn btn-primary btn-lg" onclick="openForm();" href="#" role="button">Lets Get It Started!</a>
        </p>
      </div>
      

<div id="form">
    <form class="form-inline">
        <h3 class="display-6">Enter First Year's Name</h3>
      <div class="form-group mx-sm-3 mb-2">
        <label for="insertName" class="sr-only">name</label>
        <input type="text" class="form-control" id="insertName" placeholder="Harry Potter">
      </div>
      <button id="sort" type="submit" class="btn btn-primary mb-2">Sort</button>
    </form>
</div>

<div id="studentCard"></div>

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<!--<script src="main.js"></script>-->
</body>

任何建议或解决方案将不胜感激。谢谢

【问题讨论】:

  • 添加 HTML 示例可能很有用,但我马上注意到的一件事是,您似乎对多张卡片使用相同的 ID (&lt;div id="cardContainer"&gt;)。 id 应该只适用于页面上的单个元素。您可以将类用于具有相同名称的多个元素,您可以像数组一样逐步遍历它们
  • 我添加了我的 html 以获得更多上下文

标签: javascript dom button click innerhtml


【解决方案1】:
  1. 您正在分配 student.length = 0。您的 if 语句应如下所示:

if(students.length == 0){}.

  1. 您的 expelStudentEvent 函数会删除您的卡片,因为它会根据您卡片的长度删除所有内容。

试试这样的:

const sortBuilder = (sortingHat) => {

let domString = '';
for(let i = 0; i < sortingHat.length; i++){
    domString +=    `<div id="cardContainer">`
    domString +=    `<div class="card" style="width: 18rem;">`
    domString +=        `<div class="card-body">`
    domString +=        `<h5 class="cardTitle">${sortingHat[i].name}</h5>`
    domString +=        `<p class="card-text">${sortingHat[i].house}</p>`
    domString +=        `<a onclick="expelStudentEvent(${i})" id="${sortingHat[i].id}" href="#" class="expel">Expel</a>`
    domString +=        `</div>`
    domString +=    `</div>`
    domString +=    `</div>`
}

printToDom('studentCard', domString)

};

const expelStudentEvent = (index) => {
    students.splice(index,1);
    sortBuilder(students);
};

【讨论】:

  • 我已经进行了更改,但结果仍然相同。我的按钮仍在删除所有已填充的卡片,而不仅仅是一张卡片。谢谢你的评论
  • 事实上,这样做会带来另一个问题,即所有卡片都被保存(不太确定如何..),当我删除它们然后添加新卡片时,它会显示我所有其他卡片ve“开除”
  • 您的卡片已被删除,因为您的删除函数仅在整个学生数组上运行,并将所有 dom 元素清空。您只需根据学生 id 找到卡片并从学生数组中拼接即可。
  • 我很抱歉,但我将如何做到这一点?我不确定如何获取卡片的 ID。根据我对代码的理解,我为卡片提供了一个 ID,该 ID 等于为它们在数组中的位置生成的数字(如果我错了,请纠正我)如果这是真的,我将如何获取所述卡片的 ID?它看起来像 students.studentId 吗?
  • 哇,这太棒了.. 我想我完全想多了。所以如果我理解正确的话。它不起作用,因为就像你说的那样,我正在根据数组的长度删除卡片。设置为 0,如果我将它拼接到 1 的数组中,它将创建一个空白的 domstring?
猜你喜欢
  • 2021-01-05
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
  • 2019-04-18
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
相关资源
最近更新 更多