我正在用javascript构建代码,并且由于将函数作为方法分成对象,并且每个方法都调用另一个,因此我按照格式更改了代码的组织。我以前的代码工作正常,但是由于某种原因,这不是。 简要解释我的代码: 我的代码将创建模型中列出的猫的图片,并创建一个包含猫名的侧边栏。然后,当我单击名称时,它将为猫和猫的图片添加事件监听器。图片也是可点击的。因此,单击它会增加图片底部的点击次数。 我希望这将有助于阅读代码更有意义。 希望能得到一些帮助。 谢谢
/* ================= Model ================= */
//creating an array object that holds all the cats in it
var model = {
cats: [
{
"name": "Poplinre",
"image": "poplinre.jpg",
"clicks": 0
},
{
"name": "Chewie",
"image": "chewie.jpg",
"clicks": 0
},
{
"name": "Snow",
"image": "snow.jpg",
"clicks": 0
},
{
"name": "Cowboy",
"image": "cowboy.jpg",
"clicks": 0
}
]
};
/*=============== Octopus ==================*/
var octopus = {
init: function(){
view.createCats();
view.navBarSide();
},
//function that loads the page and then add eventlistener to each image
addImgListeners: function(){
let idList = document.querySelectorAll("img");
let elemArray = [...idList];
elemArray.forEach( function(elem) {
elem.addEventListener('click', function(e){
octopus.increaseClick(e);
}, false);
});
},
//function that increases the clicks with every click
increaseClick: function(e){
let element = e.target.classList[0];
cats[element].clicks +=1;
view.postClick(element);
},
//function that adds listeners to the side bar
listListeners: function(){
document.getElementById("list").addEventListener('click', function(e){
let targetPic = e.target.innerHTML;
let parentTarget = document.querySelector("."+targetPic+"").parentElement;
view.showPic(parentTarget);
});
}
};
/*============== View ===================*/
var view = {
//view model bulding the view
//function that creates the cats in the dom element
createCats: function(){
let addingCats = "";
(model.cats).forEach(function(cat, catIndex, cats){
addingCats += "<div class='catsP' style='display:none;'><div class='nameC "+cat.name+"'>" + cat.name +"</div><img src='" + cat.image + "' class='"+catIndex.toString()+"'><div id='" + catIndex.toString() + "'>" + cat.clicks.toString() + "</div></div>";
});
var picDiv = document.getElementById("main");
picDiv.innerHTML = addingCats;
octopus.addImgListeners();
},
//function that opens the cat needed and hides it
showPic: function(x){
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
},
// view model bulding the nav bar side
//function that adds cats to the navbar
navBarSide: function(){
let barEl = document.getElementById("list");
(model.cats).forEach( function(cat, catIndex, cats){
barEl.innerHTML += "<li><a>"+ cat.name +"</a></li>";
});
octopus.listListeners();
},
//post the click to the image to show the user
postClick: function(el){
document.getElementById(""+el+"").innerHTML = "Clicks: " + model.cats[el].clicks;
}
};
document.onload = function(){
octopus.init();
};
答案 0 :(得分:0)
使用window.onload代替document.onload。当DOM准备就绪时,后者会触发,这可能在加载图像/脚本之前发生。 window.onload等待整个文档被加载。
还有其他较小的错误,如评论中所述。