我希望在页面上通过JavaScript动态创建的“电影标题”和“电影年份”能够应用我在CSS文件中设置的样式。目前,这些由JavaScript生成的元素仅以普通的黑色文本显示。
这些类的样式应当表现为更大的白色文本,并使用Google字体。
我遗漏了什么?
请查看以下HTML、CSS和原生JS代码:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... 头部元数据和链接样式表 ... -->
</head>
<body>
<!-- ... 页面结构 ... -->
<input type="text" id="movie-search-box" onkeyup="findMovies()" />
<i class="fa-solid fa-magnifying-glass fa-lg" aria-hidden="true"></i>
<div class="result-grid" id="result-grid">
<!-- 动态内容将插入此处 -->
</div>
<script src="script.js"></script>
</body>
</html>
CSS:
/* ... 其他CSS规则 ... */
.movie-title {
color: white;
font-size: 1.4rem;
margin: 10px 0 0 0;
text-transform: uppercase;
}
.movie-year {
color: white;
font-size: 1rem;
margin: 10px 0 0 0;
text-transform: uppercase;
}
/* ... 其余CSS定义 ... */
JS:
const movieSearchBox = document.getElementById("movie-search-box");
function findMovies() {
const searchTerm = movieSearchBox.value;
const resultsGrid = document.getElementById("result-grid");
if (searchTerm.length > 2) {
fetch(`http://www.omdbapi.com/?s=${searchTerm}*&apikey=dd3f37db`)
.then(response => response.json())
.then(movieResults => {
movieResults.Search.forEach(movie => {
const movieCard = document.createElement("div");
movieCard.classList.add("movie-card");
resultsGrid.appendChild(movieCard);
const movieTitle = document.createElement("h3");
movieTitle.classList.add("movie-title");
// 这里应该是appendChild而不是append
movieTitle.textContent = movie.Title;
movieCard.appendChild(movieTitle);
const movieYear = document.createElement("h4");
movieYear.classList.add("movie-year");
movieYear.textContent = ` (${movie.Year})`;
movieCard.appendChild(movieYear);
console.log(movie.Title);
});
})
.catch(error => console.log(error));
}
}