我一直在研究使用 JS 从一张图像切换到另一张图像的不同方法。我尝试使用 classList.toggle 和现在的 eventListener 方法,我认为该方法可以正常工作,但该按钮并非在所有情况下都工作。我还想使用 .textContent 更改按钮的文本。我意识到我的一些语法是浅蓝色的。想知道我错过了什么。我检查了控制台几次但没有发现问题。
我尝试了使用直接图像切换的声明功能,它起作用了,但是带有事件侦听器的箭头功能不起作用。这就是我想用的。我正在准备面试,需要证明我可以使用事件监听器方法来切换图像。
<!Doctype html>
<html lang="en">
<head>
<title>About Us</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>ABOUT US</h1>
<a href="#bottompg">Jump to Bottom Page</a>
<button id="showGiftCardBtn">
Open Me
</button>
<img id="discountCode" src="images/gift.png.gif" alt="letters and numbers on a white background" class="code" style="display:none">
<script src="script.js"></script>
</body>
</html>
JavaScript:
const showGiftCard = document.getElementById("ShowGiftCardBtn");
const showCodeImage = document.getElementById("discountCode");
showGiftCard.addEventListener("click", () => {
showCodeImage.style.dispaly = "block";
let cardButton = document.getElementById('showGiftCardBtn')
console.log(cardButton)
cardButton.textContent = " Your code! 10% off any of our products or services. Thank You For Your Bussiness"
});
您在 getElementById("ShowGiftCardBtn") 中存在拼写错误,它应该是“showGiftCardBtn”,其中带有与按钮元素的 id 匹配的小写“s”,并且 showCodeImage.style.dispaly = "block"; 中存在拼写错误。它应该是显示而不是显示。
const showGiftCard = document.getElementById("showGiftCardBtn");
const showCodeImage = document.getElementById("discountCode");
showGiftCard.addEventListener("click", () => {
showCodeImage.style.display = "block";
let cardButton = document.getElementById('showGiftCardBtn');
cardButton.textContent = "Your code! 10% off any of our products or services. Thank You For Your Business";
});
这段代码应该可以工作。