0

我正在尝试为 a中的标签设置一个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)的没有意义。

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

4

2 回答 2

1

<a>您可以在创建它们时自动为 -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;
}

然后你可以使用document.getElementById('dynamicCellId_X')

于 2013-01-04T20:40:24.533 回答
1

尝试沿着这些方向做一些事情......

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";
};

笔记:

  1. addEventListener当您通过方法将函数分配为事件处理程序时,this函数内的值是触发事件的 DOM 元素。
  2. for 的第二个参数addEventListener是一个函数,它只是一个对象,就像 JavaScript 中的其他所有东西一样。因此,您可以使用一个立即调用的函数表达式,该表达式返回一个包含实际事件处理代码的函数。
  3. this如果您是 JavaScript 新手,那么的值可能会很棘手。如果您查看我的 IIFE,它是在该addEventListener方法的“click”参数之后的括号内定义的函数,您会注意到我this在最后(就在参数之前)作为参数传入false。我在这里所做的是thisbuildData等同于test.prototype. 但是,IIFE 将其视为self参数,因此在返回的函数中,它使用参数调用self's (ie test.prototype)edit方法,this在这种情况下,参数是触发事件的元素。
  4. test.prototype.edit将元素作为其单个参数并更改背景颜色。
于 2013-01-04T20:44:36.920 回答