[英]javascript attached click event issue
我正在尝试将click
事件设置为TD
内的<a>
标签
我有
test.prototype.buildData = function() {
cell = createElement('td', {innerHTML: "<a class='link' onclick='"+this.edit(this)+"'>"+ value + "</a>"});
this.table.appendChild(cell);
//many cells..all need to attached the click event
}
test.prototype.edit=function(this){
this.style.backgroundColor='red'
}
我想修改单击的cell
background color
。 我还需要将click
事件仅注册到<a>
标签。 我知道我的this.edit(this)
没有意义。
反正有没有这样做? 非常感谢!
您可以在创建时自动将ID分配给<a>
-s
var newCellId = 0;
test.prototype.buildData = function() {
cell = createElement('td',
{innerHTML: "<a class='link' id='dynamicCellId_"+String(newCellId)+"'"+ value + "</a>"});
this.table.appendChild(cell);
newCellId +=1;
}
然后,您可以使用document.getElementById('dynamicCellId_X')
跟踪所有这些document.getElementById('dynamicCellId_X')
尝试这些方面的东西......
test.prototype.buildData = function (value) {
var cell = document.createElement("td"),
anchor = document.createElement("a");
anchor.className = "link";
anchor.addEventListener("click", (function (self) {
return function () {
self.edit(this);
};
})(this), false);
anchor.innerHTML = value;
cell.appendChild(anchor);
this.table.appendChild(cell);
};
test.prototype.edit = function (el) {
el.style.backgroundColor = "red";
};
笔记:
addEventListener
方法将函数指定为事件处理程序时,函数中的this
值是触发事件的DOM元素。 addEventListener
的第二个参数是一个函数,它就像JavaScript中的其他所有对象一样。 因此,您可以使用立即调用的函数表达式,该表达式返回包含实际事件处理代码的函数。 this
可能会非常棘手。 如果你看一下我的IIFE,它是在addEventListener
方法的“click”参数之后的括号内定义的函数,你会注意到我将this
作为参数传递到最后(在false
参数之前) )。 我在这里做的是从buildData
方法的角度传递this
的值,它等同于test.prototype
。 然而,IIFE认为这是self
论证,因此在返回的函数中,它使用参数this
调用self
(即test.prototype
) edit
方法,在这种情况下,该参数是触发事件的元素。 test.prototype.edit
将一个元素作为其单个参数并更改背景颜色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.