简体   繁体   中英

javascript attached click event issue

I am trying to setup a click event to a <a> tag inside a TD

I have

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'  
}

I want to modify the clicked cell background color . I also need to register click event ONLY to the <a> tag. I know my this.edit(this) doesn't make sense.

Are there anyways to do this? Thanks a lot!

You could automatically assign ids to the <a> -s as you create them

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

Then you can trace all of them using document.getElementById('dynamicCellId_X')

Try something along these lines...

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

NOTES:

  1. When you assign a function as an event handler via the addEventListener method, the value of this within the function is the DOM element that triggered the event.
  2. The second argument for addEventListener is a function which is simply an object like everything else in JavaScript. Therefore, you can use an immediately invoked function expression that returns a function that would contain the actual event handling code.
  3. The value of this can be tricky if you're new to JavaScript. If you look at my IIFE which is the function defined inside the parentheses right after the "click" argument for the addEventListener method you'll note that I'm passing this in as an argument to that at the end (right before the false argument). What I'm doing here is passing the value of this from the perspective of the buildData method which equates to test.prototype . The IIFE sees that as the self argument, though, so in the returned function it calls self 's (ie test.prototype ) edit method with the argument this which is in this case the element that triggered the event.
  4. test.prototype.edit takes an element as its single argument and changes the background color.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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