html-Javascript-if语句未从数组中返回正确的图像(始终在后面)
发布时间:2022-05-12 08:44:16 262
相关标签: # css
我有一系列图片:
const characterImages = ["images/jerry-senfeld.png", "images/george-costanza.png", "images/elaine-benes.png", "images/cosmo-kramer.png"]
我有另一个函数,它从基本 API 中提取一些数据并更新一个简单的 HTML 页面。if 语句查看 innerHTML 以确定存在哪个字符,并基于此设置图像的 src 属性。一切都按预期工作,但是显示的图像始终是报价后面的 1 个索引点。因此,例如,如果他们的 innerHTML<h2>说“George”,我可以期待 jerry-seinfeld.png 图像显示。我一直在兜圈子,任何帮助将不胜感激。下面的代码。谢谢!
//Define our variables
const headerTag = document.querySelector("h2");
const quoteTag = document.querySelector(".quote");
let characterImage = document.querySelector(".characterImage");
const characterImages = [
"images/jerry-senfeld.png",
"images/george-costanza.png",
"images/elaine-benes.png",
"images/cosmo-kramer.png",
];
var x;
const getQuote = () => {
fetch("https://seinfeld-quotes.herokuapp.com/quotes")
.then((response) => response.json())
.then((jsonData) => {
quoteTag.innerHTML = jsonData.quotes[x].quote;
headerTag.innerHTML = jsonData.quotes[x].author;
});
};
// images function to go below:
const getImage = () => {
if (headerTag.innerHTML == "Jerry") {
characterImage.setAttribute("src", characterImages[0]);
} else if (headerTag.innerHTML == "George") {
characterImage.setAttribute("src", characterImages[1]);
} else if (headerTag.innerHTML == "Elaine") {
characterImage.setAttribute("src", characterImages[2]);
} else if (headerTag.innerHTML == "Kramer") {
characterImage.setAttribute("src", characterImages[3]);
} else {
characterImage.setAttribute("src", "images/placeholder-image.png");
}
};
document.querySelector("button").addEventListener("click", function (event) {
x = Math.floor(Math.random() * 422);
getQuote();
getImage();
});
HTML(相关部分):
<div class="main-quote">
<h2></h2>
<img src="images/placeholder-image.png" class="characterImage" alt="character image">
<p class="quote"></p>
<button class="button2">Click!</button>
</div>
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报