Hướng dẫn how to add book in javascript? - làm thế nào để thêm sách trong javascript?

Bạn tạo phần tử sách tốt, nhưng trong các dòng:

let titleContent = document.createTextNode("Title: " + books[0].title);
let authorContent = document.createTextNode("Author: " + books[0].author);
let categoryContent = document.createTextNode("Category: " + books[0].category);

Bạn tiếp tục chèn cuốn sách đầu tiên.

Hơn nữa, bạn tiếp tục tạo một ul mới mỗi khi bạn thêm một phần tử ____10 mới và bạn thêm tất cả các thuộc tính của cuốn sách của bạn vào các yếu tố danh sách khác nhau.

Vì vậy, bạn cần phải tái cấu trúc mã của mình để thêm tất cả thông tin sổ sách vào một yếu tố danh sách và sau đó thêm nó vào danh sách.

Đầu tiên, bạn cần tạo một phần tử ul với ID

class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
2 ngay sau phần tử
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
3 của bạn, trong HTML của bạn.

Và sau đó bạn cần thay đổi mã của mình bằng cách lấy phần tử ul bên ngoài chức năng

class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
5 của bạn và sử dụng nó để thêm một yếu tố sách mới:

class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);

Subarticle này cho thấy cách xác định một trang/biểu mẫu để tạo các đối tượng

class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
6. Điều này phức tạp hơn một chút so với các trang tương đương
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
7 hoặc
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
8 vì chúng tôi cần có và hiển thị các bản ghi
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
7 và
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
8 ở dạng
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
6 của chúng tôi.

Phương pháp xác thực và vệ sinh nhập khẩu

Open /Controllers /bookControll.js và thêm dòng sau ở đầu tệp:/controllers/bookController.js, and add the following line at the top of the file:

const { body, validationResult } = require("express-validator");

Bộ điều khiển Get Get Route

Tìm phương thức bộ điều khiển

const { body, validationResult } = require("express-validator");
2 đã xuất và thay thế nó bằng mã sau.

// Display book create form on GET.
exports.book_create_get = (req, res, next) => {
  // Get all authors and genres, which we can use for adding to our book.
  async.parallel(
    {
      authors(callback) {
        Author.find(callback);
      },
      genres(callback) {
        Genre.find(callback);
      },
    },
    (err, results) => {
      if (err) {
        return next(err);
      }
      res.render("book_form", {
        title: "Create Book",
        authors: results.authors,
        genres: results.genres,
      });
    }
  );
};

Điều này sử dụng mô -đun Async (được mô tả trong hướng dẫn Express Phần 5: Hiển thị dữ liệu thư viện) để lấy tất cả các đối tượng

class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
7 và
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
8. Chúng sau đó được truyền đến chế độ xem
const { body, validationResult } = require("express-validator");
5 dưới dạng các biến có tên
const { body, validationResult } = require("express-validator");
6 và
const { body, validationResult } = require("express-validator");
7 (cùng với trang
const { body, validationResult } = require("express-validator");
8).
const { body, validationResult } = require("express-validator");
5
as variables named
const { body, validationResult } = require("express-validator");
6 and
const { body, validationResult } = require("express-validator");
7 (along with the page
const { body, validationResult } = require("express-validator");
8).

Bộ điều khiển tuyến đường

Tìm phương thức bộ điều khiển

const { body, validationResult } = require("express-validator");
9 đã xuất và thay thế nó bằng mã sau.

// Handle book create on POST.
exports.book_create_post = [
  // Convert the genre to an array.
  (req, res, next) => {
    if (!Array.isArray(req.body.genre)) {
      req.body.genre =
        typeof req.body.genre === "undefined" ? [] : [req.body.genre];
    }
    next();
  },

  // Validate and sanitize fields.
  body("title", "Title must not be empty.")
    .trim()
    .isLength({ min: 1 })
    .escape(),
  body("author", "Author must not be empty.")
    .trim()
    .isLength({ min: 1 })
    .escape(),
  body("summary", "Summary must not be empty.")
    .trim()
    .isLength({ min: 1 })
    .escape(),
  body("isbn", "ISBN must not be empty").trim().isLength({ min: 1 }).escape(),
  body("genre.*").escape(),

  // Process request after validation and sanitization.
  (req, res, next) => {
    // Extract the validation errors from a request.
    const errors = validationResult(req);

    // Create a Book object with escaped and trimmed data.
    const book = new Book({
      title: req.body.title,
      author: req.body.author,
      summary: req.body.summary,
      isbn: req.body.isbn,
      genre: req.body.genre,
    });

    if (!errors.isEmpty()) {
      // There are errors. Render form again with sanitized values/error messages.

      // Get all authors and genres for form.
      async.parallel(
        {
          authors(callback) {
            Author.find(callback);
          },
          genres(callback) {
            Genre.find(callback);
          },
        },
        (err, results) => {
          if (err) {
            return next(err);
          }

          // Mark our selected genres as checked.
          for (const genre of results.genres) {
            if (book.genre.includes(genre._id)) {
              genre.checked = "true";
            }
          }
          res.render("book_form", {
            title: "Create Book",
            authors: results.authors,
            genres: results.genres,
            book,
            errors: errors.array(),
          });
        }
      );
      return;
    }

    // Data from form is valid. Save book.
    book.save((err) => {
      if (err) {
        return next(err);
      }
      // Successful: redirect to new book record.
      res.redirect(book.url);
    });
  },
];

Cấu trúc và hành vi của mã này gần như giống hệt như để tạo đối tượng

class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
8 hoặc
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
7. Đầu tiên chúng tôi xác nhận và vệ sinh dữ liệu. Nếu dữ liệu không hợp lệ thì chúng tôi sẽ hiển thị lại biểu mẫu cùng với dữ liệu ban đầu được nhập bởi người dùng và danh sách các thông báo lỗi. Nếu dữ liệu hợp lệ, chúng tôi sẽ lưu bản ghi
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
6 mới và chuyển hướng người dùng đến trang chi tiết sách.

Sự khác biệt chính liên quan đến mã xử lý hình thức khác là cách chúng ta vệ sinh thông tin thể loại. Biểu mẫu trả về một mảng các mục

class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
8 (trong khi đối với các trường khác, nó sẽ trả về một chuỗi). Để xác thực thông tin, trước tiên chúng tôi chuyển đổi yêu cầu thành một mảng (cần thiết cho bước tiếp theo).

[
  // Convert the genre to an array.
  (req, res, next) => {
    if (!Array.isArray(req.body.genre)) {
      req.body.genre =
        typeof req.body.genre === "undefined" ? [] : [req.body.genre];
    }
    next();
  },
  // …
];

Sau đó, chúng tôi sử dụng một ký tự đại diện (

// Display book create form on GET.
exports.book_create_get = (req, res, next) => {
  // Get all authors and genres, which we can use for adding to our book.
  async.parallel(
    {
      authors(callback) {
        Author.find(callback);
      },
      genres(callback) {
        Genre.find(callback);
      },
    },
    (err, results) => {
      if (err) {
        return next(err);
      }
      res.render("book_form", {
        title: "Create Book",
        authors: results.authors,
        genres: results.genres,
      });
    }
  );
};
4) trong chất khử trùng để xác nhận riêng từng mục của mảng thể loại. Mã dưới đây cho thấy cách - điều này chuyển thành "vệ sinh mọi mục dưới khóa
// Display book create form on GET.
exports.book_create_get = (req, res, next) => {
  // Get all authors and genres, which we can use for adding to our book.
  async.parallel(
    {
      authors(callback) {
        Author.find(callback);
      },
      genres(callback) {
        Genre.find(callback);
      },
    },
    (err, results) => {
      if (err) {
        return next(err);
      }
      res.render("book_form", {
        title: "Create Book",
        authors: results.authors,
        genres: results.genres,
      });
    }
  );
};
5".

[
  // …
  body("genre.*").escape(),
  // …
];

Sự khác biệt cuối cùng đối với mã xử lý biểu mẫu khác là chúng ta cần truyền trong tất cả các thể loại và tác giả hiện có sang biểu mẫu. Để đánh dấu các thể loại đã được người dùng kiểm tra, chúng tôi lặp lại tất cả các thể loại và thêm tham số

// Display book create form on GET.
exports.book_create_get = (req, res, next) => {
  // Get all authors and genres, which we can use for adding to our book.
  async.parallel(
    {
      authors(callback) {
        Author.find(callback);
      },
      genres(callback) {
        Genre.find(callback);
      },
    },
    (err, results) => {
      if (err) {
        return next(err);
      }
      res.render("book_form", {
        title: "Create Book",
        authors: results.authors,
        genres: results.genres,
      });
    }
  );
};
6 vào các thể loại trong dữ liệu bài đăng của chúng tôi (như được sao chép trong đoạn mã bên dưới).

// Mark our selected genres as checked.
for (const genre of results.genres) {
  if (book.genre.includes(genre._id)) {
    // Current genre is selected. Set "checked" flag.
    genre.checked = "true";
  }
}

Lượt xem

Tạo /views /book_form.pug và sao chép trong văn bản bên dưới./views/book_form.pug and copy in the text below.

extends layout

block content
  h2= title

  form(method='POST' action='')
    div.form-group
      label(for='title') Title:
      input#title.form-control(type='text', placeholder='Name of book' name='title' required='true' value=(undefined===book ? '' : book.title) )
    div.form-group
      label(for='author') Author:
      select#author.form-control(type='select', placeholder='Select author' name='author' required='true' )
        - authors.sort(function(a, b) {let textA = a.family_name.toUpperCase(); let textB = b.family_name.toUpperCase(); return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;});
        for author in authors
          if book
            option(value=author._id selected=(author._id.toString()===book.author._id.toString() ? 'selected' : false) ) #{author.name}
          else
            option(value=author._id) #{author.name}
    div.form-group
      label(for='summary') Summary:
      textarea#summary.form-control(type='textarea', placeholder='Summary' name='summary' required='true') #{undefined===book ? '' : book.summary}
    div.form-group
      label(for='isbn') ISBN:
      input#isbn.form-control(type='text', placeholder='ISBN13' name='isbn' value=(undefined===book ? '' : book.isbn) required='true')
    div.form-group
      label Genre:
      div
        for genre in genres
          div(style='display: inline; padding-right:10px;')
            input.checkbox-input(type='checkbox', name='genre', id=genre._id, value=genre._id, checked=genre.checked )
            label(for=genre._id) #{genre.name}
    button.btn.btn-primary(type='submit') Submit

  if errors
    ul
      for error in errors
        li!= error.msg

Cấu trúc và hành vi xem gần giống như đối với mẫu Genere_form.pug.genre_form.pug template.

Sự khác biệt chính là cách chúng tôi triển khai các trường loại lựa chọn:

class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
7 và
class Book {
    constructor(title,author,category) {
        this.title = title;
        this.author = author;
        this.category = category;
    }
}

let btn = document.getElementById('submit');
let elementUl = document.getElementById('book-list');

let books = [];

function addElement(book) {
    
    // Convert these elements to p, in order to hold your book info.    
    let elementTitle = document.createElement('p');
    let elementAuthor = document.createElement('p');
    let elementCategory = document.createElement('p');
    
    // The list element that will hold all book info.
    let bookElement = document.createElement('li');

    let titleContent = document.createTextNode("Title: " + book.title);
    let authorContent = document.createTextNode("Author: " + book.author);
    let categoryContent = document.createTextNode("Category: " + book.category);

    elementTitle.appendChild(titleContent);
    elementAuthor.appendChild(authorContent);
    elementCategory.appendChild(categoryContent);
    
    // Add all book info to list element.
    bookElement.appendChild(elementTitle);
    bookElement.appendChild(elementAuthor);
    bookElement.appendChild(elementCategory);
    
    // Add list element to list.
    elementUl.appendChild(bookElement);
}

function submitForm(event) {
    event.preventDefault();
    
    let title = document.getElementById('title').value;
    let author = document.getElementById('author').value;
    let category = document.getElementById('category').value;

    let book = new Book(title,author,category);

    books.push(book);     

    addElement(book);
      
}

btn.addEventListener('click',submitForm);
8.

  • Tập hợp các thể loại được hiển thị dưới dạng hộp kiểm, sử dụng giá trị
    // Display book create form on GET.
    exports.book_create_get = (req, res, next) => {
      // Get all authors and genres, which we can use for adding to our book.
      async.parallel(
        {
          authors(callback) {
            Author.find(callback);
          },
          genres(callback) {
            Genre.find(callback);
          },
        },
        (err, results) => {
          if (err) {
            return next(err);
          }
          res.render("book_form", {
            title: "Create Book",
            authors: results.authors,
            genres: results.genres,
          });
        }
      );
    };
    
    9 mà chúng tôi đặt trong bộ điều khiển để xác định xem hộp có nên được chọn hay không.
  • Tập hợp các tác giả được hiển thị dưới dạng danh sách thả xuống theo thứ tự theo thứ tự một lựa chọn. Nếu người dùng trước đây đã chọn tác giả sách (nghĩa là khi sửa các giá trị trường không hợp lệ sau khi gửi biểu mẫu ban đầu hoặc khi cập nhật chi tiết sách), tác giả sẽ được chọn lại khi biểu mẫu được hiển thị. Ở đây chúng tôi xác định những gì tác giả chọn bằng cách so sánh ID của tùy chọn tác giả hiện tại với giá trị được nhập trước đây bởi người dùng (được chuyển qua biến
    // Handle book create on POST.
    exports.book_create_post = [
      // Convert the genre to an array.
      (req, res, next) => {
        if (!Array.isArray(req.body.genre)) {
          req.body.genre =
            typeof req.body.genre === "undefined" ? [] : [req.body.genre];
        }
        next();
      },
    
      // Validate and sanitize fields.
      body("title", "Title must not be empty.")
        .trim()
        .isLength({ min: 1 })
        .escape(),
      body("author", "Author must not be empty.")
        .trim()
        .isLength({ min: 1 })
        .escape(),
      body("summary", "Summary must not be empty.")
        .trim()
        .isLength({ min: 1 })
        .escape(),
      body("isbn", "ISBN must not be empty").trim().isLength({ min: 1 }).escape(),
      body("genre.*").escape(),
    
      // Process request after validation and sanitization.
      (req, res, next) => {
        // Extract the validation errors from a request.
        const errors = validationResult(req);
    
        // Create a Book object with escaped and trimmed data.
        const book = new Book({
          title: req.body.title,
          author: req.body.author,
          summary: req.body.summary,
          isbn: req.body.isbn,
          genre: req.body.genre,
        });
    
        if (!errors.isEmpty()) {
          // There are errors. Render form again with sanitized values/error messages.
    
          // Get all authors and genres for form.
          async.parallel(
            {
              authors(callback) {
                Author.find(callback);
              },
              genres(callback) {
                Genre.find(callback);
              },
            },
            (err, results) => {
              if (err) {
                return next(err);
              }
    
              // Mark our selected genres as checked.
              for (const genre of results.genres) {
                if (book.genre.includes(genre._id)) {
                  genre.checked = "true";
                }
              }
              res.render("book_form", {
                title: "Create Book",
                authors: results.authors,
                genres: results.genres,
                book,
                errors: errors.array(),
              });
            }
          );
          return;
        }
    
        // Data from form is valid. Save book.
        book.save((err) => {
          if (err) {
            return next(err);
          }
          // Successful: redirect to new book record.
          res.redirect(book.url);
        });
      },
    ];
    
    0). Điều này được nhấn mạnh ở trên!

    Lưu ý: Nếu có lỗi trong biểu mẫu đã gửi, thì khi biểu mẫu được đổi lại, ID của tác giả sách mới và ID tác giả của các cuốn sách hiện có thuộc loại

    // Handle book create on POST.
    exports.book_create_post = [
      // Convert the genre to an array.
      (req, res, next) => {
        if (!Array.isArray(req.body.genre)) {
          req.body.genre =
            typeof req.body.genre === "undefined" ? [] : [req.body.genre];
        }
        next();
      },
    
      // Validate and sanitize fields.
      body("title", "Title must not be empty.")
        .trim()
        .isLength({ min: 1 })
        .escape(),
      body("author", "Author must not be empty.")
        .trim()
        .isLength({ min: 1 })
        .escape(),
      body("summary", "Summary must not be empty.")
        .trim()
        .isLength({ min: 1 })
        .escape(),
      body("isbn", "ISBN must not be empty").trim().isLength({ min: 1 }).escape(),
      body("genre.*").escape(),
    
      // Process request after validation and sanitization.
      (req, res, next) => {
        // Extract the validation errors from a request.
        const errors = validationResult(req);
    
        // Create a Book object with escaped and trimmed data.
        const book = new Book({
          title: req.body.title,
          author: req.body.author,
          summary: req.body.summary,
          isbn: req.body.isbn,
          genre: req.body.genre,
        });
    
        if (!errors.isEmpty()) {
          // There are errors. Render form again with sanitized values/error messages.
    
          // Get all authors and genres for form.
          async.parallel(
            {
              authors(callback) {
                Author.find(callback);
              },
              genres(callback) {
                Genre.find(callback);
              },
            },
            (err, results) => {
              if (err) {
                return next(err);
              }
    
              // Mark our selected genres as checked.
              for (const genre of results.genres) {
                if (book.genre.includes(genre._id)) {
                  genre.checked = "true";
                }
              }
              res.render("book_form", {
                title: "Create Book",
                authors: results.authors,
                genres: results.genres,
                book,
                errors: errors.array(),
              });
            }
          );
          return;
        }
    
        // Data from form is valid. Save book.
        book.save((err) => {
          if (err) {
            return next(err);
          }
          // Successful: redirect to new book record.
          res.redirect(book.url);
        });
      },
    ];
    
    1. Vì vậy, để so sánh chúng, chúng ta phải chuyển đổi chúng thành chuỗi trước. If there is an error in the submitted form, then, when the form is to be re-rendered, the new book author's id and the existing books's authors ids are of type
    // Handle book create on POST.
    exports.book_create_post = [
      // Convert the genre to an array.
      (req, res, next) => {
        if (!Array.isArray(req.body.genre)) {
          req.body.genre =
            typeof req.body.genre === "undefined" ? [] : [req.body.genre];
        }
        next();
      },
    
      // Validate and sanitize fields.
      body("title", "Title must not be empty.")
        .trim()
        .isLength({ min: 1 })
        .escape(),
      body("author", "Author must not be empty.")
        .trim()
        .isLength({ min: 1 })
        .escape(),
      body("summary", "Summary must not be empty.")
        .trim()
        .isLength({ min: 1 })
        .escape(),
      body("isbn", "ISBN must not be empty").trim().isLength({ min: 1 }).escape(),
      body("genre.*").escape(),
    
      // Process request after validation and sanitization.
      (req, res, next) => {
        // Extract the validation errors from a request.
        const errors = validationResult(req);
    
        // Create a Book object with escaped and trimmed data.
        const book = new Book({
          title: req.body.title,
          author: req.body.author,
          summary: req.body.summary,
          isbn: req.body.isbn,
          genre: req.body.genre,
        });
    
        if (!errors.isEmpty()) {
          // There are errors. Render form again with sanitized values/error messages.
    
          // Get all authors and genres for form.
          async.parallel(
            {
              authors(callback) {
                Author.find(callback);
              },
              genres(callback) {
                Genre.find(callback);
              },
            },
            (err, results) => {
              if (err) {
                return next(err);
              }
    
              // Mark our selected genres as checked.
              for (const genre of results.genres) {
                if (book.genre.includes(genre._id)) {
                  genre.checked = "true";
                }
              }
              res.render("book_form", {
                title: "Create Book",
                authors: results.authors,
                genres: results.genres,
                book,
                errors: errors.array(),
              });
            }
          );
          return;
        }
    
        // Data from form is valid. Save book.
        book.save((err) => {
          if (err) {
            return next(err);
          }
          // Successful: redirect to new book record.
          res.redirect(book.url);
        });
      },
    ];
    
    1. So to compare them we must convert them to strings first.

Nó trông như thế nào?

Chạy ứng dụng, mở trình duyệt của bạn thành

// Handle book create on POST.
exports.book_create_post = [
  // Convert the genre to an array.
  (req, res, next) => {
    if (!Array.isArray(req.body.genre)) {
      req.body.genre =
        typeof req.body.genre === "undefined" ? [] : [req.body.genre];
    }
    next();
  },

  // Validate and sanitize fields.
  body("title", "Title must not be empty.")
    .trim()
    .isLength({ min: 1 })
    .escape(),
  body("author", "Author must not be empty.")
    .trim()
    .isLength({ min: 1 })
    .escape(),
  body("summary", "Summary must not be empty.")
    .trim()
    .isLength({ min: 1 })
    .escape(),
  body("isbn", "ISBN must not be empty").trim().isLength({ min: 1 }).escape(),
  body("genre.*").escape(),

  // Process request after validation and sanitization.
  (req, res, next) => {
    // Extract the validation errors from a request.
    const errors = validationResult(req);

    // Create a Book object with escaped and trimmed data.
    const book = new Book({
      title: req.body.title,
      author: req.body.author,
      summary: req.body.summary,
      isbn: req.body.isbn,
      genre: req.body.genre,
    });

    if (!errors.isEmpty()) {
      // There are errors. Render form again with sanitized values/error messages.

      // Get all authors and genres for form.
      async.parallel(
        {
          authors(callback) {
            Author.find(callback);
          },
          genres(callback) {
            Genre.find(callback);
          },
        },
        (err, results) => {
          if (err) {
            return next(err);
          }

          // Mark our selected genres as checked.
          for (const genre of results.genres) {
            if (book.genre.includes(genre._id)) {
              genre.checked = "true";
            }
          }
          res.render("book_form", {
            title: "Create Book",
            authors: results.authors,
            genres: results.genres,
            book,
            errors: errors.array(),
          });
        }
      );
      return;
    }

    // Data from form is valid. Save book.
    book.save((err) => {
      if (err) {
        return next(err);
      }
      // Successful: redirect to new book record.
      res.redirect(book.url);
    });
  },
];
2, sau đó chọn liên kết tạo sách mới. Nếu mọi thứ được thiết lập chính xác, trang web của bạn sẽ trông giống như ảnh chụp màn hình sau. Sau khi bạn gửi một cuốn sách hợp lệ, nó sẽ được lưu và bạn sẽ được đưa vào trang Chi tiết Sách.

Hướng dẫn how to add book in javascript? - làm thế nào để thêm sách trong javascript?

Bước tiếp theo