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!
Try something along these lines…
NOTES:
addEventListenermethod, the value ofthiswithin the function is the DOM element that triggered the event.addEventListeneris 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.thiscan 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 theaddEventListenermethod you’ll note that I’m passingthisin as an argument to that at the end (right before thefalseargument). What I’m doing here is passing the value ofthisfrom the perspective of thebuildDatamethod which equates totest.prototype. The IIFE sees that as theselfargument, though, so in the returned function it callsself‘s (i.e.test.prototype)editmethod with the argumentthiswhich is in this case the element that triggered the event.test.prototype.edittakes an element as its single argument and changes the background color.