0

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?

2
  • What is this obj and where it is defined? Commented Dec 21, 2012 at 19:44
  • what is obj? what is task? Commented Dec 21, 2012 at 19:45

2 Answers 2

1

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

task.prototype.changeName=function() { alert(this.id); }; 
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

Confusing. Don't do this. Methods are expected to be called in the context of the corresponding instance.
@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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.