使用for循环创建元素和事件侦听器
Creating elements and event listeners with a for loop
我有一个对象数组,我定义了一个函数来使用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()
相关文章:
- 如何在for循环中添加事件侦听器
- 未命中服务器发送的事件侦听器
- 如何覆盖原型中的事件侦听器
- 无法将事件侦听器附加到画布
- 如何在d3.js中自定义事件侦听器
- 在es6中,将带有回调的事件侦听器设置为可迭代的
- 事件侦听器未在chrome扩展中的options.js中启动
- IE8更改文本区域上的事件侦听器不工作
- 将事件侦听器添加到文档,而不是签入元素存在,然后添加事件侦听器
- javascript删除事件侦听器
- 我应该/如何清除mousemove JQuery事件侦听器
- 在JQuery中使用谷歌地图Api事件/侦听器
- 如何使用我的Jquery代码创建委托事件侦听器
- 'mousemove'画布中的事件侦听器-指针仅在最后一个矩形中更改
- 为什么此事件侦听器不工作
- 是否可以在数字输入框中的小按钮中添加事件侦听器
- 在Google Chrome扩展中添加事件侦听器
- SVG元素在转换后会丢失事件侦听器
- jQuery事件侦听器多次启动
- 如何在不删除类似侦听器的情况下从父对象中删除jQuery事件侦听器