简体   繁体   English

将 object 传递给 function 时出现意外标识符

[英]Unexpected identifier when passing object to function

When im trying to pass object to function, i get "Uncaught syntaxError: Unexpected Identifier".当我试图将 object 传递给 function 时,我得到“未捕获的语法错误:意外的标识符”。

Code looks like this:代码如下所示:

myLibrary = [{author: "J.K.Rowling",
    title: "Harry Potter and the Philosopher's Stone",
    numberOfPages: 223,
    read: true
}];

function displayBooksTable () {
    let table = document.getElementById("books-list");
    if(myLibrary.length === 0) {
        table.textContent = '';
        return;
    }
    table.textContent = '';
    myLibrary.forEach((book, index) => {
        let row = table.insertRow(-1);
        let title = row.insertCell(0);
        let author = row.insertCell(1);
        let pages = row.insertCell(2);
        let read = row.insertCell(3);
        let del = row.insertCell(4);
        title.innerHTML = book.title;
        author.innerHTML = book.author;
        pages.innerHTML = book.numberOfPages;
        read.innerHTML = '<button id="read-button" onclick="updateReadButton('+book+')">read</button>'
        del.innerHTML = '<button id="del-button" onclick="deleteButton('+index+')">Delete</button>'
    })
    console.table(myLibrary);
}

const updateReadButton = (book) => {
    book.read = !book.read;
    displayBooksTable();
}

Issue is with this:问题在于:

read.innerHTML = '<button id="read-button" onclick="updateReadButton('+book+')">read</button>'

and

const updateReadButton = (book) => {
    book.read = !book.read;
    displayBooksTable();
}

What am I doing wrong?我究竟做错了什么? How can i pass book object to function from forEach loop?我如何从 forEach 循环将书 object 传递给 function?

The book is an object, but you're turning it into a string when inserting it into HTML markup here:book是 object,但是在将其插入 HTML 标记时,您将其变成了字符串:

onclick="updateReadButton('+book+')"

resulting in problems.导致问题。

Best to avoid inline handlers entirely - they have problems with quote escaping and a crazy scope chain.最好完全避免内联处理程序- 他们在引用 escaping疯狂的 scope 链方面存在问题。 Add the event listener to the element using addEventListener .使用addEventListener将事件侦听器添加到元素。

read.innerHTML = '<button>read</button>';
del.innerHTML = '<button>Delete</button>';
read.children[0].addEventListener('click', () => updateReadButton(book));
del.children[0].addEventListener('click', () => deleteButton(index));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM