我是JavaScript的新手,现在我学习如何在编写代码时分离关注点(MVC架构)。所以我有这个代码,我点击猫的图像和计数器变量增加,每次点击图像。点击计数与猫图像一起显示。我的index.html文件如下所示:
// Model
var model = {
currentCat: null,
totalCats: [
{
clickCount: 0,
name: 'Shiro',
imgSrc: 'images/cat1.jpg',
resetSrc: 'images/reseticon.png'
},
{
clickCount: 0,
name: 'Shadow',
imgSrc: 'images/cat2.jpg',
resetSrc: 'images/reseticon.png'
},
{
clickCount: 0,
name: 'Pasta',
imgSrc: 'images/cat1.jpg',
resetSrc: 'images/reseticon.png'
}
]
};
//Octopus
var octopus={
init: function(){
model.currentCat = model.totalCats[0];
catListview.init();
catView.init();
},
getCurrentCat: function(){
return model.currentCat;
},
getCats: function(){
return model.totalCats;
},
setCurrentCat: function(cat){
model.currentCat = cat;
},
incrementCounter: function(){
model.currentCat.clickCount++;
catView.render();
},
resetCounter: function(){
model.currentCat.catCount=0;
catView.render();
}
};
//View
var catView = {
init: function(){
this.catEl = document.getElementById('cat');
this.catNameEl = document.getElementById('catName');
this.catCountEl = document.getElementById('catCount');
this.catImageEl = document.getElementById('catImage');
this.resetEl = document.getElementById('reset-button');
this.catImageEl.addEventListener('click',function(){
octopus.incrementCounter();
});
this.resetEl.addEventListener('click',function(){
octopus.resetCounter();
});
this.render();
},
render: function(){
var currentCat = octopus.getCurrentCat();
this.catCountEl.textContent = currentCat.clickCount;
this.catImageEl.src = currentCat.imgSrc;
this.catNameEl.textContent = currentCat.name;
this.resetEl.src = currentCat.resetSrc;
}
};
var catListview = {
init: function(){
this.catListEl = document.getElementById('cat-list');
this.render();
},
render: function(){
var cats = octopus.getCats();
this.catListEl.innerHTML = '';
for(var i=0;i<cats.length;i++){
thiscat = cats[i];
var elem = document.createElement('li');
elem.textContent = thiscat.name;
elem.addEventListener('click',(function(thiscatCopy){
return function(){
octopus.setCurrentCat(thiscatCopy);
catView.render();
};
})(thiscat));
this.catListEl.appendChild(elem);
}
}
};
octopus.init();
&#13;
img:hover{
border: 1px solid #000;
}
&#13;
<title>Cat Clicker Premium</title>
<ul id="cat-list"></ul>
<div id="cat">
<h2 id="catName"></h2>
<div id="catCount"></div>
<img id="catImage" src="" alt="image of cat">
</div>
<img id="reset-button" src="" alt="reset cat counter">
&#13;
除了重置计数器之外,一切正常。计数器完全没有重置。任何人都可以告诉我,我做错了。提前致谢。
PS:八达通只是一个有趣的名字。它实际上是底层控制器。
答案 0 :(得分:0)
重置功能错误
resetCounter: function(){
model.currentCat.clickCount=0;
catView.render();
}