Я делаю упражнение на основе шаблонов javascript от Udacity.Нам сказали сделать страницу с изображениями кошек, их именами и счетчиками, которые увеличиваются каждый раз, когда мы нажимаем на изображение кошки.Мне удалось сделать это, как вы можете видеть в моем коде, с помощью forloop, который добавил слушателей событий к каждому изображению.После того, как мы это сделали, нам сказали, что мы должны это изменить.Теперь нам нужно было составить список или индекс с именем каждого кота, и когда мы щелкнули по любому из имен, изображение этого кота должно появиться где-то на странице вместе с его именем и счетчиком.Моя проблема возникает, когда я пытаюсь получить доступ к innerHTML элементов изображения с помощью forloop, чтобы добавить их в «mylist».Ничего не происходит, когда я пишу эту часть кода, и если я использую forEach для создания свойства, содержащего innerhtml, чтобы поместить это свойство (например, object.name) в элементы списка в html, он создает список, который показывает«undefined» вместо innerHTML, который я хочу показать (имя кота).Это означает, что что-то не так с html-объектами, содержащимися в массиве listOfImages.Что мне нужно сделать?Есть ли более разумный подход для этого?Почему я не могу получить доступ к innerHTML img?спасибо
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cat clicker!</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<style type="text/css">
* {
margin: 20;
box-sizing: border-box;
}
body {
background: white;
}
</style>
<body>
<div class = "container">
<h1><i><b>Gatitos</b></i></h1>
<br>
<br>
</div>
<div id = 0><img src="cat1.jpg" id = 0 width = 470 height = 340><h1 style = "color:red">Lucas</h1></div>
<div id = 1><img src="cat2.jpg" id = 1 width = 470 height = 340><h1 style = "color:red">Martin</h1></div>
<div id = 2><img src="cat3.jpg" id = 2 width = 470 height = 340><h1 style = "color:red">Pedro</h1></div>
<div id = 3><img src="cat4.jpg" id = 3 width = 470 height = 340><h1 style = "color:red">Felix</h1></div>
<div id = 4><img src="cat5.jpg" id = 4 width = 470 height = 340><h1 style = "color:red">Felipe</h1></div>
<div>
<ul id = "namesList">
<!-- here i'd like to add the innerHTMLs of each img tag -->
</ul>
</div>
<script type="text/javascript">
var listOfImages = Array.from(document.getElementsByTagName("img"));
var listOfCounters = [];
//this forloop creates a counter for each image and appends that counter to a list of h1 counter elements
for (var i = 0; i<listOfImages.length; i++){
//adds the links to the list
var catName = document.createElement("h2");
var catNameText = document.createTextNode(listOfImages[i].innerHTML);
catName.appendChild(catNameText);
document.getElementById("namesList").appendChild(catName);
//adds the counter to each image
var h1 = document.createElement("h1");
var t = document.createTextNode(0);
h1.appendChild(t);
document.getElementById(i).appendChild(h1);
//adds the counter to the list of counters
listOfCounters.push(h1);
};
//adds the counters objects as properties of each image element, and then adds click listeners to each image, in order to update each counter
listOfImages.forEach(function(element, index){
var count = 0;
element.nombre = element.innerHTML;
element.counter = listOfCounters[index];
element.addEventListener("click", function(){
element.counter.innerHTML = count +1;
count += 1;
});
});
</script>
</body>
</html>