gpt4 book ai didi

javascript - 无法访问在另一种方法中初始化的元素

转载 作者:可可西里 更新时间:2023-11-01 13:42:20 24 4
gpt4 key购买 nike

$(function() {
var model = {
currentCat: null,
cats: [{
name: "Felix",
clickCounter: 0,
srcImage: "cat0.jpg"
},
{
name: "Lucas",
clickCounter: 0,
srcImage: "cat1.jpg"
},
{
name: "Martin",
clickCounter: 0,
srcImage: "cat2.jpg"
},
{
name: "Pedro",
clickCounter: 0,
srcImage: "cat3.jpg"
}
]
};

var octopus = {
init: function() {
indexView.init();
displayView.init();
},
getCats: function() {
return model.cats;
},
getCurrentCat: function() {
return model.currentCat;
},
setCurrentCat: function(cat) {
model.currentCat = cat;
},
updateClickCounter: function() {
model.currentCat.clickCounter++;
displayView.render();
}
};

var displayView = {
init: function() {
this.imgSection = document.getElementById("imageSection");
this.catImg = document.getElementById("cat-img");
this.catName = document.getElementById("cat-name");
this.catCounter = document.getElementById("cat-counter");

this.catImg.addEventListener("click", function() {
octopus.updateClickCounter();
})
this.render()
},
render: function() {
var cat = octopus.getCurrentCat();

this.catName.textContent = cat.name;
this.catCounter.textContent = cat.clickCounter;
this.catImg.src = cat.srcImage;
}
};


var indexView = {
init: function() {

this.list = $("#list")
this.render();

},
render: function() {
cats = octopus.getCats();
for (i = 0; i < cats.length; i++) {
cat = cats[i];
listElement = document.createElement("li");
listElement.textContent = cat.name;

listElement.addEventListener("click", (function(copyCat) {
octopus.setCurrentCat(copyCat);
displayView.render();
})(cat));
};
}
};



octopus.init();
});
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>Cat clicker</title>
<link rel="stylesheet" href="css/cat.css">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css" />
</head>

<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/cat.js"></script>

<h1 id="header"> Gatitos! </h1>

<div id="catIndex">
<h2 id="indexTitle">Index</h2>
<ul id="list">
<!-- here we have the index with the cats names -->
</ul>
</div>
<div id="imageSection">

<h2 id="cat-name"></h2>
<div id="cat-counter"></div>
<img src="" id="cat-img">
</div>

</body>

</html>

displayView 对象中,我只能在初始化方法中访问通过 getElementById 获得的 html 元素(我可以访问 catImg 当我在 init 方法中添加事件监听器时)。当我尝试在 render 方法中访问这些元素时,问题就来了。当您运行它时,当您从 init 方法(this.catImgthis.catName 调用所有元素时,它会返回 undefined这个.catCounter)。为什么返回 undefined

最佳答案

您必须将“this”绑定(bind)到您的事件处理程序,查看Javascript scope addEventListener and this关于如何将 this 的范围限定到您的事件监听器。

关于javascript - 无法访问在另一种方法中初始化的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53736371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com