[英]Trying to get alt text to show when a user clicks on an image
我可能在這里遺漏了一些非常重要的東西,但我一直在處理這段代碼,而且我一遍又一遍地陷入同樣的錯誤——我不確定我做錯了什么。
這是我的 HTML
<html lang="en">
<head>
<meta charset="utf-8">
<title>Images to Text</title>
<link rel="stylesheet" href="styles.css" type="text/css"/>
</head>
<body>
<h1>Some of my Favorite Animals.</h1>
<h2>Capybara & Mantis Shrimp</h2>
<div id='showAlt'>
<img src="capybaraman.jpg" height="190" alt="A picture of a capybara in the arms of a man, showing that they are about the size of dogs but look comparable to guinea pigs.">
<img src="capybaramonkey.jpg" width="300" alt="A picture of a capybara with monkeys petting and on top of the capybara.">
<img src="capybarabird.png" width="300" alt="A picture of a capybara laying in the mud. There is also a bird sitting on top of them.">
<img src="mantisshrimp.jpg" width="300" alt="A picture of a mantis shrimp with its' arms open, they are rainbow with large eyes. They have small wing-like structures coming from the sides of their bodies.">
<img src="mantisbody.jpg" width="230" alt="A picture showing the mantis shrimp's body, it is long and looks like a lobster's tail with the same texture.">
<img src="mantisclose.jpg" width="300" alt="A picture close up to a mantis shrimp's face, you can see their large eyes and their 'mouth'.">
</div>
<div id="clickToShow"></div>
<script src="imagetotext.js"></script>
</body>
</html>
這是我的 JavaScript
let altText = document.getElementById('clickToShow');
let clicker = document.getElementById('showAlt');
for (let x = 0; x < document.images.length; x++) {
altText[x].addEventListener('click', imageToText);
}
function imageToText() {
let clickImage = this.alt;
clicker.textContent = clickImage;
}
每次用戶單擊圖像時,我都試圖添加一個 for 循環,它會顯示其替代文本,但我不斷收到錯誤消息,說它無法讀取未定義的 imageToText 的屬性 addEventListener。 我認為這可能是 HTML 中的 JS 太高了,因為它是未定義的,但即使在將我的腳本標簽向下移動之后,這種情況仍然存在。 我還想使用事件監聽器標簽——我還沒學過 jQuery。 任何幫助都會很棒。 我現在感覺被我的代碼卡住了。
每次用戶單擊圖像時,我都試圖添加一個 for 循環
然后將事件偵聽器添加到每個圖像 - 您當前正在嘗試將點擊偵聽器添加到altText[x]
,但altText
是單個元素,一個<div>
- 它不是一個集合。
你也可能不想清除包含圖像的#showAlt
div,因為那樣它們都會消失 - 你想將它添加到另一個 div 嗎?
for (const img of document.querySelectorAll('img')) {
img.addEventListener('click', imageToText);
}
function imageToText() {
altText.textContent = this.alt;
}
這是錯誤
for (let x = 0; x < document.images.length; x++) {
altText[x].addEventListener('click', imageToText);
}
你從 document.getElementById('clickToShow'); 得到 altText; 正確的?
里面,沒有數組,這就是為什么 addEventListener 無法讀取它
將其更改為:
for (let x = 0; x < document.images.length; x++) {
clicker[x].addEventListener('click', imageToText);
}
並將其更改為
function imageToText() {
let clickImage = this.alt;
altText.textContent = clickImage;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.