繁体   English   中英

javascript附加点击事件问题

[英]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";
};

笔记:

  1. 通过addEventListener方法将函数指定为事件处理程序时,函数中的this值是触发事件的DOM元素。
  2. addEventListener的第二个参数是一个函数,它就像JavaScript中的其他所有对象一样。 因此,您可以使用立即调用的函数表达式,该表达式返回包含实际事件处理代码的函数。
  3. 如果您不熟悉JavaScript, this可能会非常棘手。 如果你看一下我的IIFE,它是在addEventListener方法的“click”参数之后的括号内定义的函数,你会注意到我将this作为参数传递到最后(在false参数之前) )。 我在这里做的是从buildData方法的角度传递this的值,它等同于test.prototype 然而,IIFE认为这是self论证,因此在返回的函数中,它使用参数this调用self (即test.prototypeedit方法,在这种情况下,该参数是触发事件的元素。
  4. test.prototype.edit将一个元素作为其单个参数并更改背景颜色。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM