我们的任务

我们将创建一些非常基本的数据,然后使用普通的 JS 从 DOM 创建 CRUD 操作(创建、读取、更新、删除)。

设置

  • 在计算机某处的文件夹中创建三个文件。

    • index.html
    • app.js
    • style.css

这应该在您的 index.html 中

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />
    <script src="app.js" defer></script>
  </head>
  <body>
    <main></main>
    <div></div>
  </body>
</html>

注意 Javascript 脚本标签中的 defer 关键字。这样做的目的是告诉浏览器在浏览器呈现 HTML 文档之前不要运行 JS,这样它就存在于网站上的任何代码引用元素之前。

什么是 DOM

DOM(文档对象模型)是 Javascript 与网站交互的方式。实际发生的是浏览器读取您的 html 文件并构建一个表示每个元素的 javascript 对象树,该对象称为“文档”。您可以操作此对象,这些更改将在浏览器屏幕中反映给用户。

数据

在您的 javascript 中,让我们创建一个对象数组以呈现给 DOM。

const people = [
  { name: "Alex Merced", age: 35 },
  { name: "Bob Jones", age: 65 },
  { name: "Steve Smith", age: 22 },
  { name: "Macie Willis", age: 32 },
  { name: "John Jingle", age: 40 },
]

渲染数据 (cRud)

所以我们现在要做的就是定位你的html中的main元素,将数组中的所有数据一一添加到DOM中。理想情况下,我们不想一遍又一遍地编写逻辑,因此循环将成为我们的朋友,for of 循环使循环数组变得容易。

///////////////////////
// Global Data
///////////////////////

const people = [
  { name: "Alex Merced", age: 35 },
  { name: "Bob Jones", age: 65 },
  { name: "Steve Smith", age: 22 },
  { name: "Macie Willis", age: 32 },
  { name: "John Jingle", age: 40 },
]

//document.querySelector takes a css selector and returns the first element that matches that selector
const mainDiv = document.querySelector("main") // returns the one main element in our html

///////////////////////
// Functions
///////////////////////

//define function for rendering current data to DOM, use this whenever data changes
const renderData = () => {
  //empty of the main div of any existing content
  mainDiv.innerHTML = ""

  //let us loop over the people array
  for (person of people) {
    const personH1 = document.createElement("h1") // Creates new h1 element
    personH1.innerText = `${person.name} is ${person.age} years old` //ads text to the h1
    mainDiv.appendChild(personH1) //append the h1 to the main element
  }
}

////////////////////
// Main App Logic
////////////////////

renderData() //call the render data function for the initial rendering of the data

阅读评论以了解每个喜欢的人在做什么。

添加新项目(Crud)

让我们在 html 的 div 中添加一个表单

<body>
  <main></main>
  <div id="form">
    <input type="text" name="name" placeholder="name" />
    <input type="number" name="age" placeholder="age" />
    <button id="createitem">Submit</button>
  </div>
</body>

现在是我们的 javascript,我们将添加一个函数,将表单数据添加到一个新对象中并将其推送到数组中,然后我们将调用我们的 renderdata 函数来更新人员列表。

///////////////////////
// Global Data
///////////////////////

const people = [
  { name: "Alex Merced", age: 35 },
  { name: "Bob Jones", age: 65 },
  { name: "Steve Smith", age: 22 },
  { name: "Macie Willis", age: 32 },
  { name: "John Jingle", age: 40 },
]

//document.querySelector takes a css selector and returns the first element that matches that selector
const mainDiv = document.querySelector("main") // returns the one main element in our html

//below we will add our form inputs to some global variables
const nameInput = document.querySelector('input[name="name"]') //selecting the input with name property "name"
const ageInput = document.querySelector('input[name="age"]') //selecting the input with name property "name"
const createButton = document.querySelector("button#createitem") //select button with id "createitem"

///////////////////////
// Functions
///////////////////////

//define function for rendering current data to DOM, use this whenever data changes
const renderData = () => {
  //empty of the main div of any existing content
  mainDiv.innerHTML = ""

  //let us loop over the people array
  for (person of people) {
    const personH1 = document.createElement("h1") // Creates new h1 element
    personH1.innerText = `${person.name} is ${person.age} years old` //ads text to the h1
    mainDiv.appendChild(personH1) //append the h1 to the main element
  }
}

const createData = () => {
  const name = nameInput.value //store value from name input into name variable
  const age = ageInput.value //store value from age input into age variable
  const newPerson = { name, age } // create new person object
  people.push(newPerson) //push the new person object into the array
  renderData() //render the data again so it reflects the new data
}

////////////////////
// Main App Logic
////////////////////
renderData() //call the render data function for the initial rendering of the data
createButton.addEventListener("click", createData) //trigger create data function whenever createButton is clicked

阅读每行代码的作用的注释。

删除项目(cruD)

现在更新和删除是事情开始变得棘手的地方。我们需要能够告诉我们要删除或更新哪个项目。正常的 for...of 循环实际上并没有内置的方式来访问索引,因为它在数组上循环。forEach 数组方法确实允许我们拥有可用的索引,因此我们需要重构我们的渲染数据函数。

为什么?因为当我们将每个项目渲染到 DOM 时,我们需要添加更新和删除按钮,这是最好的地方。删除和更新按钮需要有索引来执行所需的操作,因此我们需要在索引可用且在范围内时在循环期间处理所有这些。(这些时候我们开始明白为什么人们如此喜欢 Vue、Angular、React 和 Svelte)

///////////////////////
// Global Data
///////////////////////

const people = [
  { name: "Alex Merced", age: 35 },
  { name: "Bob Jones", age: 65 },
  { name: "Steve Smith", age: 22 },
  { name: "Macie Willis", age: 32 },
  { name: "John Jingle", age: 40 },
]

//document.querySelector takes a css selector and returns the first element that matches that selector
const mainDiv = document.querySelector("main") // returns the one main element in our html

//below we will add our form inputs to some global variables
const nameInput = document.querySelector('input[name="name"]') //selecting the input with name property "name"
const ageInput = document.querySelector('input[name="age"]') //selecting the input with name property "name"
const createButton = document.querySelector("button#createitem") //select button with id "createitem"

///////////////////////
// Functions
///////////////////////

//define function for rendering current data to DOM, use this whenever data changes
const renderData = () => {
  //empty of the main div of any existing content
  mainDiv.innerHTML = ""

  //let us loop over the people array
  people.forEach((person, index) => {
    const personH1 = document.createElement("h1") // Creates new h1 element

    const buttonContainer = document.createElement("aside") //create aside to store update/delete buttons

    //Delete Button
    const deleteButton = document.createElement(`button`) //create delete button
    deleteButton.id = index
    deleteButton.innerText = "Delete" //make the delete button say "Delete"
    deleteButton.addEventListener("click", event => {
      people.splice(index, 1) //remove the element at the current index
      renderData() //re-render the updated data to the DOM
    })
    buttonContainer.appendChild(deleteButton) //apend the delete button

    personH1.innerText = `${person.name} is ${person.age} years old` //ads text to the h1
    mainDiv.appendChild(personH1) //append the h1 to the main element
    mainDiv.appendChild(buttonContainer) //append container of update and delete button
  })
}

const createData = () => {
  const name = nameInput.value //store value from name input into name variable
  const age = ageInput.value //store value from age input into age variable
  const newPerson = { name, age } // create new person object
  people.push(newPerson) //push the new person object into the array
  renderData() //render the data again so it reflects the new data
}

////////////////////
// Main App Logic
////////////////////
renderData() //call the render data function for the initial rendering of the data
createButton.addEventListener("click", createData) //trigger create data function whenever createButton is clicked

更新按钮 (crUd)

所以现在我们将添加一个更新按钮,与我们添加删除按钮的方式非常相似,但需要更多步骤。我们需要一个额外的表单来处理更新,使用另一个按钮来处理更新正确的元素。所以更新按钮不会更新,而是用现有数据填充更新表单,当在该表单上点击提交按钮时,数据会更新并重新呈现。

index.html

<body>
  <main></main>
  <div id="form">
    <input type="text" name="name" placeholder="name" />
    <input type="number" name="age" placeholder="age" />
    <button id="createitem">Submit</button>
  </div>
  <div id="form2">
    <input type="text" name="updatename" placeholder="updated name" />
    <input type="number" name="updateage" placeholder="updated age" />
    <button id="updateitem">Submit</button>
  </div>
</body>

app.js

///////////////////////
// Global Data
///////////////////////

const people = [
  { name: "Alex Merced", age: 35 },
  { name: "Bob Jones", age: 65 },
  { name: "Steve Smith", age: 22 },
  { name: "Macie Willis", age: 32 },
  { name: "John Jingle", age: 40 },
]

//document.querySelector takes a css selector and returns the first element that matches that selector
const mainDiv = document.querySelector("main") // returns the one main element in our html

//below we will add our form inputs to some global variables
const nameInput = document.querySelector('input[name="name"]') //selecting the input with name property "name"
const ageInput = document.querySelector('input[name="age"]') //selecting the input with name property "name"
const createButton = document.querySelector("button#createitem") //select button with id "createitem"

//below we will add our update form inputs to some global variables
const updateName = document.querySelector('input[name="updatename"]') //selecting the input with name property "name"
const updateAge = document.querySelector('input[name="updateage"]') //selecting the input with name property "name"
const updateFormButton = document.querySelector("button#updateitem") //select button with id "createitem"

///////////////////////
// Functions
///////////////////////

//define function for rendering current data to DOM, use this whenever data changes
const renderData = () => {
  //empty of the main div of any existing content
  mainDiv.innerHTML = ""

  //let us loop over the people array
  people.forEach((person, index) => {
    const personH1 = document.createElement("h1") // Creates new h1 element

    const buttonContainer = document.createElement("aside") //create aside to store update/delete buttons

    //Delete Button
    const deleteButton = document.createElement(`button`) //create delete button
    deleteButton.id = index
    deleteButton.innerText = "Delete" //make the delete button say "Delete"
    deleteButton.addEventListener("click", event => {
      people.splice(index, 1) //remove the element at the current index
      renderData() //re-render the updated data to the DOM
    })
    buttonContainer.appendChild(deleteButton) //apend the delete button

    //Update Button
    const updateButton = document.createElement(`button`) //create update button
    updateButton.id = index
    updateButton.innerText = "Update" //make the delete button say "Delete"
    updateButton.addEventListener("click", event => {
      updateName.value = person.name //set form to show current name
      updateAge.value = person.age //set form to show current age
      updateFormButton.setAttribute("toupdate", index) //custom attribute to use in the button event later
    })
    buttonContainer.appendChild(updateButton) //apend the delete button

    personH1.innerText = `${person.name} is ${person.age} years old` //ads text to the h1
    mainDiv.appendChild(personH1) //append the h1 to the main element
    mainDiv.appendChild(buttonContainer) //append container of update and delete button
  })
}

const createData = () => {
  const name = nameInput.value //store value from name input into name variable
  const age = ageInput.value //store value from age input into age variable
  const newPerson = { name, age } // create new person object
  people.push(newPerson) //push the new person object into the array
  renderData() //render the data again so it reflects the new data
}

const updateData = event => {
  const index = event.target.getAttribute("toupdate") //get index we stored via custom attribute
  const name = updateName.value //get value from form
  const age = updateAge.value //get value from form
  people[index] = { name, age } //replace existing object at that index with a new with updated values
  renderData() //update the DOM with the new data
}

////////////////////
// Main App Logic
////////////////////
renderData() //call the render data function for the initial rendering of the data
createButton.addEventListener("click", createData) //trigger create data function whenever createButton is clicked
updateFormButton.addEventListener("click", updateData) //trigger update data function when updateButton is clicked

好了,你得到了完整的 CRUD 功能。唯一的问题是每次更改数据时都要跟踪更新 DOM,这非常令人沮丧。这是 Vue、React、Angular 和 Svelte 等库真正让生活变得更轻松的主要方式之一,因为它们将数据绑定到您的 UI,因此当数据更新时,您的 UI 应该会自动更新,从而省去了重新思考的麻烦-渲染自己。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐