javascript附加点击事件问题

javascript附加点击事件问题,javascript,Javascript,我正在尝试将单击事件设置为标签(位于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 attache

我正在尝试将
单击事件设置为
标签(位于
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'  
}
test.prototype.buildData=function(){
cell=createElement('td',{innerHTML:“+value+”});
此.table.appendChild(单元格);
//许多单元格..都需要附加单击事件
}
test.prototype.edit=函数(this){
这个.style.backgroundColor='red'
}
我想修改单击的
单元格
背景色
。我还需要将
单击
事件仅注册到
标记。我知道我的
这个。编辑(这个)
没有意义


有办法做到这一点吗?非常感谢

您可以在创建时自动为
-s分配ID

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;
}
var newCellId=0;
test.prototype.buildData=函数(){
cell=createElement('td',

{innerHTML:“尝试以下内容

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
    的值可能会很棘手。如果你看看我的iLife,它是在
    addEventListener
    方法的“click”参数之后的括号中定义的函数,你会注意到我在最后将
    this
    作为参数传递给它(就在
    false
    参数之前)。我在这里做的是从
    buildData
    方法的角度传递
    this
    的值,该方法等同于
    test.prototype
    。IIFE将其视为
    self
    参数,因此在返回的函数中调用
    self
    (即
    test.prototype
    edit
    方法,参数为
    this
    ,在本例中,该参数是触发事件的元素
  • test.prototype.edit
    将元素作为其单个参数,并更改背景颜色

  • 首先…不要使用onclick。。。