我正在尝试设置 click
事件到<a>
TD
内的标签
我有
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)
没有意义。
有办法做到这一点吗?非常感谢!
最佳答案
尝试一些类似的事情......
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 中的其他所有内容一样。因此,您可以使用立即调用的函数表达式,该表达式返回一个包含实际事件处理代码的函数。
- 如果您不熟悉 JavaScript,
this
的值可能会很棘手。如果您查看我的 IIFE,它是在addEventListener
方法的“click”参数后面的括号内定义的函数,您会注意到我正在将this
传递给作为最后的参数(就在false
参数之前)。我在这里所做的是从buildData
方法的 Angular 传递this
的值,该值相当于test.prototype
。不过,IIFE 将其视为self
参数,因此在返回的函数中它调用self
的(即test.prototype
)edit
方法,其参数this
在本例中是触发事件的元素。 test.prototype.edit
将一个元素作为其单个参数并更改背景颜色。
关于javascript附加点击事件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14164516/