我有一个对象数组,我已经使用this关键字定义了一个引用这个对象的函数。
var catArray = [toodles, whiskers, cornelius, poko, flufflepuss];
function catClicker() {
currentCat.textContent = this.name;
photo.src = this.src;
console.log("clicked on " + this.name);
catNow = this;
clicker.textContent = this.clicks;
}
我正在尝试使用for循环将列表项添加到html ul并同时为我的函数添加事件侦听器。为什么不起作用?
for (var i = 0; i < catArray.length; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode(catArray[i].name));
item.addEventListener("click", catClicker);
}
答案 0 :(得分:0)
您需要使用Function.prototype.bind来设置正确的this
范围。
item.addEventListener('click', catClicker.bind(catArray[i]));
答案 1 :(得分:0)
我有这个工作,也许你可以解决你的代码有什么问题。我很难说出你的问题是什么,因为你发布的内容中缺少重要的代码。
function whenReady(){
for (var i = 0; i < catArray.length; i++) {
var item = document.createElement('li');
var d
item.appendChild(document.createTextNode(catArray[i].name));
item.attributes.setNamedItem(
(d=document.createAttribute('data-catArray-idx'),d.value=i,d)
)
document.body.appendChild(item)
item.addEventListener("click", catClicker);
catClicks.set(catArray[i],{clicks:0})
}
catView=CatView().setCat(catArray[0]).appendToElement(document.body)
}
var catView
var catClicks=new WeakMap()
var catArray = [
{name: "toodles",url:"images/toodles.jpg",height:100,width:150},
{name: "whiskers",url:"images/whiskers.jpg",height:100,width:150},
{name: "cornelius",url:"images/cornelius.jpg",height:100,width:150},
{name: "poko", url:"images/poko.jpg",height:100,width:150},
{name: "flufflepuss",url:"images/flufflepuss.jpg",height:100,width:150}
]
var clicks=0
function catClicker() {
catView.setCat(catArray[this.attributes['data-catarray-idx'].value])
console.log("clicked on " + catView.selectedCat.name);
catClicks.get(catView.selectedCat).clicks++
}
var catViewId=0
var p=CatView.prototype
p.setCat=function(cat){
this.selectedCat=cat
this.update()
return this
}
p.appendToElement = function(element){
element.appendChild(this.catView)
return this
}
p.template= (name,photoURL) =>
`<img src="${photoURL}" height=100 width=100><span>${name}</span>`
p.update=function(){
this.catView.innerHTML =
this.template(
this.selectedCat.name, this.selectedCat.url
)
return this
}
p.toString=function(){this.selectedCat.name + 'view'}
function CatView(){
var me,cv,id
id = 'catView'+catViewId++
me = Object.create(CatView.prototype)
cv = me.catView = document.createElement('div')
cv.id = id;
return me
}
whenReady()