1

我正在尝试将 onclick 功能附加到每个 a 标签。

我有

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

有没有办法做到这一点?

4

2 回答 2

1

在事件处理程序内部,this是创建事件的对象,所以这应该工作:

task.prototype.changeName=function() { alert(this.id); }; 
于 2012-12-21T19:49:16.893 回答
0

我在小提琴中创建了一个示例:http: //jsfiddle.net/dWPCS/2/

在您的事件处理程序中,对元素changeName的引用。this所以this.id返回你想要的值。

于 2012-12-21T19:51:37.317 回答