使用for循环创建元素和事件侦听器

Creating elements and event listeners with a for loop

本文关键字:事件 侦听器 元素 创建 for 循环 使用      更新时间:2023-09-26

我有一个对象数组,我定义了一个函数来使用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); 
}

您需要使用Function.prototype.bind来设置正确的this范围。

item.addEventListener('click', catClicker.bind(catArray[i]));

我已经处理好了,也许你可以从中找出你的代码出了什么问题。我很难说出你的问题是什么,因为你发布的代码中缺少了重要的部分。

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()