Hướng dẫn này sẽ dạy bạn cách tạo bảng HTML động thông qua việc sử dụng thao tác mô hình đối tượng JavaScript và tài liệu [DOM]. Số lượng hàng bảng và nội dung ô sẽ thay đổi tùy thuộc vào dữ liệu của bạn.
Trong hướng dẫn này, tôi sẽ tạo một bảng điểm cho một trò chơi video JavaScript và dữ liệu sẽ đến từ một yêu cầu tìm nạp. Nguồn dữ liệu cho ứng dụng của bạn có thể khác nhau, nhưng logic vẫn nên được áp dụng. Hướng dẫn này sẽ bao gồm ảnh chụp màn hình cho mã, kết xuất trang web và HTML đầy đủ ở mỗi bước trong hướng dẫn.
Mã thân thiện với bản sao là ở cuối. 🔥
Dữ liệu cho bảng HTML này xuất phát từ bảng cơ sở dữ liệu SQLite. Số lượng hàng sẽ thay đổi tùy thuộc vào số lượng hồ sơ trong bảng điểm.
Đây là một ví dụ về dữ liệu chúng tôi sẽ làm việc.Thẻ bảng HTML:
Một bảng HTML bao gồm một phần tử Bảng HTML này cũng sẽ bao gồm các tùy chọn và các yếu tố cho các tùy chọn kiểu dáng bổ sung. Định nghĩa thẻ: Thẻ Thẻ Thẻ Thẻ Thẻ Thẻ Chúng tôi sẽ tạo tất cả các thẻ được xác định ở trên thông qua Phương thức tài liệu. Hầu hết các tên lớp mà bạn sẽ thấy trong mã đều ở đó cho mục đích tạo kiểu và hoàn toàn tùy chọn. Kiểu dáng CSS sẽ không được thảo luận, nhưng nó sẽ có sẵn để bạn tham khảo và kiểm tra một mình. Điều đó sẽ chứa bảng của chúng tôi là như sau: Các bước để tạo bảng: Ví dụ về đối tượng singlescore đang được chuyển vào hàm tiếp theo: Cuối cùng, tôi đã đề cập rằng bảng ví dụ này dựa vào một lần tìm kiếm để nhận dữ liệu của nó. Dưới đây là mã cho Fetch cung cấp tất cả các điểm riêng cho chức năng ‘appendscores: Tôi hy vọng bạn đã tìm thấy hướng dẫn này hữu ích. Nếu bạn có bất kỳ câu hỏi, hãy hỏi họ dưới đây. Dưới đây là một video ngắn của ứng dụng mà tôi đã tạo bảng cụ thể này cho! Tất cả các mã trong đoạn trích: Tất cả các kiểu dáng CSS cho bảng trong hướng dẫn này: và một hoặc nhiều, và các phần tử.
xác định bảng HTML.
xác định một hàng trong bảng HTML. xác định một ô tiêu đề trong bảng HTML.
xác định một ô dữ liệu tiêu chuẩn trong bảng HTML. let tableHeaders = [“Global Ranking”, “Username”, “Score”, “Time Alive [seconds]”, “Accuracy [%]”]
0 được sử dụng để nhóm nội dung tiêu đề trong bảng HTML.let tableHeaders = [“Global Ranking”, “Username”, “Score”, “Time Alive [seconds]”, “Accuracy [%]”]
1 được sử dụng để nhóm nội dung cơ thể trong bảng HTML.Hướng dẫn:
let tableHeaders = [“Global Ranking”, “Username”, “Score”, “Time Alive [seconds]”, “Accuracy [%]”]
Hàm đạt được các bước được nêu ở trên. Kết xuất bảng [tại thời điểm này].singleScore = { "id": 6, "score": 115, "time_alive": 70.659, "accuracy": 17.1, "user_id": 1, "user": { "username": "daniel" }}
Chức năng đạt được các bước trên.Rendering của bảng đầy đủ.comPlete HTML cho ‘bảng điểm Div Div và bảng HTML động.const scoreDiv = document.querySelector["div.scoreboard"] // Find the scoreboard div in our htmllet tableHeaders = ["Global Ranking", "Username", "Score", "Time Alive [seconds]", "Accuracy [%]"]const createScoreboardTable = [] => {while [scoreDiv.firstChild] scoreDiv.removeChild[scoreDiv.firstChild] // Remove all children from scoreboard div [if any]let scoreboardTable = document.createElement['table'] // Create the table itselfscoreboardTable.className = 'scoreboardTable'let scoreboardTableHead = document.createElement['thead'] // Creates the table header group elementscoreboardTableHead.className = 'scoreboardTableHead'let scoreboardTableHeaderRow = document.createElement['tr'] // Creates the row that will contain the headersscoreboardTableHeaderRow.className = 'scoreboardTableHeaderRow'// Will iterate over all the strings in the tableHeader array and will append the header cells to the table header rowtableHeaders.forEach[header => {let scoreHeader = document.createElement['th'] // Creates the current header cell during a specific iterationscoreHeader.innerText = headerscoreboardTableHeaderRow.append[scoreHeader] // Appends the current header cell to the header row}]scoreboardTableHead.append[scoreboardTableHeaderRow] // Appends the header row to the table header group elementscoreboardTable.append[scoreboardTableHead]let scoreboardTableBody = document.createElement['tbody'] // Creates the table body group elementscoreboardTableBody.className = "scoreboardTable-Body"scoreboardTable.append[scoreboardTableBody] // Appends the table body group element to the tablescoreDiv.append[scoreboardTable] // Appends the table to the scoreboard div}// The function below will accept a single score and its index to create the global rankingconst appendScores = [singleScore, singleScoreIndex] => {const scoreboardTable = document.querySelector['.scoreboardTable'] // Find the table we createdlet scoreboardTableBodyRow = document.createElement['tr'] // Create the current table rowscoreboardTableBodyRow.className = 'scoreboardTableBodyRow'// Lines 72-85 create the 5 column cells that will be appended to the current table rowlet scoreRanking = document.createElement['td']scoreRanking.innerText = singleScoreIndexlet usernameData = document.createElement['td']usernameData.innerText = singleScore.user.usernamelet scoreData = document.createElement['td']scoreData.innerText = singleScore.scorelet timeData = document.createElement['td']timeData.innerText = singleScore.time_alivelet accuracyData = document.createElement['td']accuracyData.innerText = singleScore.accuracyscoreboardTableBodyRow.append[scoreRanking, usernameData, scoreData, timeData, accuracyData] // Append all 5 cells to the table rowscoreboardTable.append[scoreboardTableBodyRow] // Append the current row to the scoreboard table body}const getScores = [] => {fetch['//localhost:3000/scores'] // Fetch for all scores. The response is an array of objects that is sorted in decreasing order.then[res => res.json[]].then[scores => {createScoreboardTable[] // Clears scoreboard div if it has any children nodes, creates & appends the table// Iterates through all the objects in the scores array and appends each one to the table bodyfor [const score of scores] {let scoreIndex = scores.indexOf[score] + 1 // Index of score in score array for global ranking [these are already sorted in the back-end]appendScores[score, scoreIndex] // Creates and appends each row to the table body}}]}
.scoreboardTable {padding: 0;margin: auto;border-collapse: collapse;width: 80%;text-align: center;color: whitesmoke;}.scoreboardTableHeaderRow {color: darkorange;font-weight: bold;height: 50px;}.scoreboardTableBodyRow:nth-child[odd]{background-color: rgba[128, 128, 128, 0.050];}#latestUserScore {background-color: crimson;}.scoreboardTableBodyRow:hover{background-color: darkorange;}.scoreboardTable tr td {height: 25px;}
Chúng ta có thể tạo bảng động trong HTML không?
Làm thế nào để bạn tạo một bảng động?
Làm cách nào để tạo một phần tử động trong HTML?
Làm thế nào để bạn thêm các hàng và cột động trong HTML?
Chủ Đề