1

I am trying to attach an onclick function to every a tag.

I have

task.prototype.init=function(){  
        for (value in obj){
            var Link=document.createElement('a');
                Link.innerHTML='click';
                Link.id=value;   //I want to get the value
                Link.href='#'
                Link.onclick=this.changeName;
                document.body.appendChild(Link);
         }
}

task.prototype.changeName=function(){  

        //I want to get the clicked element id and I am not sure how to do it. 

    return false;
    }

Is there anyway to accomplish this?

Victor
  • 3,669
  • 3
  • 37
  • 42
FlyingCat
  • 14,036
  • 36
  • 119
  • 198

2 Answers2

1

Inside an event handler, this is the object that created the event, so this should work:

task.prototype.changeName=function() { alert(this.id); }; 
Wolfgang Stengel
  • 2,867
  • 1
  • 17
  • 22
0

I have created an example in a fiddle: http://jsfiddle.net/dWPCS/2/

In your event handler changeNamethe this references to the element. So this.idreturns the value you want.

T. Junghans
  • 11,385
  • 7
  • 52
  • 75
  • Confusing. Don't do this. Methods are expected to be called in the context of the corresponding instance. – katspaugh Dec 21 '12 at 20:49
  • @katspaugh I'm providing a solution. It may not be the perfect one but in the real world, no one enters code into a beauty contest. – T. Junghans Dec 22 '12 at 13:15
  • TJ., it isn't about beauty. It's about maintainability. The guy you'd provided the solution to was immediately confused and asked [a follow-up question](http://stackoverflow.com/questions/13996794/javascript-prototype-this-issue). – katspaugh Dec 22 '12 at 13:28