这个项目是一个小型的移动网站。我想通过 JS 动态地为参考书目提供 HTML。这是在 Firefox 中完美运行的代码:
let butlerBooks = [];
fetch("butler.json").then(res => {
return res.json();
}).then(loadedButlerBooks => {
console.log(loadedButlerBooks);
butlerBooks = loadedButlerBooks;
loadBooks();
}).catch(err => {
console.error(err);
});
const biblioItem = document.getElementById('biblioCards');
function loadBooks() {
butlerBooks.forEach(biblioCard => {
const biblioContent = `<div id="biblioBorder" class="biblio-card-container">
<div id="biblioTitle" class="biblio-list-item">
<div class="biblio-date">${biblioCard.year}</div>
<div class="biblio-booktitle">${biblioCard.title}</div>
</div>
<div id="biblioExpand" class="biblio-card-expand"><img src="./img/expand.png" alt="expand button"></div>
<div class="biblio-expanded">
<div class="biblio-expanded-top">
<div class="biblio-subtitle">${biblioCard.subtitle}</div>
<div id="biblioMinimize" class="biblio-minimize"><img src="./img/minimize.png" alt="minimize button"></div>
</div>
<div id="biblioSubcard" class="biblio-subcard">
<p class="biblio-booksummary">${biblioCard.summary}</p>
<a class="biblio-btn-link" href="${biblioCard.url}" target="_blank"><button id="biblioBtn" class="biblio-btn btn" type="button" name="button">View on Goodreads</button>
</div>
</div>
</div>`
biblioItem.insertAdjacentHTML('afterbegin', biblioContent);
if (biblioCard.series === "Patternist") {
console.log('I\'m a Patternist Book!');
biblioBorder.style.border = "0.2em solid #434463";
biblioBorder.style.borderLeft = "12px solid #434463";
biblioBtn.style.backgroundColor = "#434463";
biblioSubcard.style.background = "rgba(67, 68, 99, 0.3)";
} else {
biblioBorder.style.border = "0.2em solid #5EA878";
biblioBorder.style.borderLeft = "12px solid #5EA878";
biblioBtn.style.backgroundColor = "#5EA878";
biblioSubcard.style.background = "rgba(94, 168, 120, 0.3)";
}
这是代码在 Firefox 中的样子:Bibliography Desired View 这是它在其他浏览器中的样子:Other Browser's Broken view
我在 Firefox 中没有收到错误消息,但例如 Chrome 中的错误如下:
TypeError: Cannot set property 'border' of undefined
at main.js:48
at Array.forEach (<anonymous>)
at loadBooks (main.js:25)
at main.js:18
(anonymous) @ main.js:20
Promise.catch (async)
(anonymous) @ main.js:19
我不知道如何解决这个问题。是抓取问题吗?身份问题?forEach 循环问题?究竟是什么阻止了边框属性在其他浏览器中实现?大多数现代浏览器(ES6、Arrow Functions、InsertAdjacentHTML 等)都应该支持我使用的所有 JS,所以这对我来说是一个令人头疼的问题。
预先感谢您的任何帮助!