简体   繁体   English

如何在用JavaScript生成的锚标记上添加onclick事件?

[英]how to add onclick event on anchor tag that is generated with javascript?

I'm using only javascript, not jQuery or no other javascript frameworks. 我只使用javascript,而不使用jQuery或其他任何JavaScript框架。

I have created one anchor tag like: 我创建了一个锚标记,例如:

var _a = document.createElement('a');

now I want to add onclick for this tag. 现在,我想为此标签添加onclick。 I have tried following: 我尝试了以下方法:

_a.onclick = function(){ mycode(id); }

The function applies on that but the anchor tags are create in loop... so mycode(id) is always taking the last value of the loop. 该函数适用mycode(id) ,但是定位标记是在循环中创建的...因此, mycode(id)始终采用循环的最后一个值。

Can any one help me out in this ? 有人可以帮我吗?

Probably you need a function to create your handler like this: 可能您需要一个函数来创建您的处理程序,如下所示:

function createHandler( id ) {
  return function(){ mycode( id ); };
}

and then assign inside the loop 然后在循环内分配

for ( i= ... ) {
   _a.onclick = createHandler( i );
}

On the other hand you maybe should use addEventListener() ( MDN docu ) to add events to elements: 另一方面,您可能应该使用addEventListener()MDN docu )将事件添加到元素:

_a.addEventListener( 'click', createHandler( i ) );
for(var id = 0; id < 10; id++){
    var _a = document.createElement('a');
    _a.onclick = (function(id){
        return function (){
            mycode(id);
        }
    })(id);
}

That should fix it. 那应该解决它。

尝试以下操作:

_a.onclick = (function(id){return function(){ mycode(id); }})(id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM