FlyingCat
FlyingCat

Reputation: 14250

Simple javascript prototype issue

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?

Upvotes: 1

Views: 405

Answers (2)

T. Junghans
T. Junghans

Reputation: 11683

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.

Upvotes: 0

Wolfgang Stengel
Wolfgang Stengel

Reputation: 2856

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

task.prototype.changeName=function() { alert(this.id); }; 

Upvotes: 1

Related Questions