views:

101

answers:

1

I have an event handler that is called six times when I click on a link.

var elems = elem.getElementsByTagName('a');
var cntr = 0;
for(var a in elems) {
  AttachEvent(elems[cntr], 'click', function(e) {
    this.reporturl = this.href;
    document.getElementById('reportpopup').style.visibility = "visible";
    return false;
  });
}

I am using Firefox 3.5 currently so this is used for AttachEvent:

function AttachEvent(obj,evt,fnc,useCapture){
    if (!useCapture) useCapture=false;
    if (undefined == obj || null == obj) 
     return;
    if (obj.addEventListener){
     obj.addEventListener(evt,fnc,useCapture);
     return true;
    } else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
    else{
     MyAttachEvent(obj,evt,fnc);
     obj['on'+evt]=function(){ MyFireEvent(obj,evt); };
    }
}

The this.href value is the same each time, and there are only three links that match my getElementsByTagName.

So, I have attached an event to my link, and when I click on one of the three, it is called six times with the exact same link information.

Any idea why this may be happening?

+2  A: 

It looks like you're attaching the same event handler to the 0th item for as many times as there are links.

var cntr = 0;
    for(var a in elems) {
        AttachEvent(elems[cntr], 'click', function(e) {
                          ^never changes?

Secondly, in JavaScript object members, properties, array elements, etc. are all in the same collection. for(var item in obj) will run once for every available member of obj. If it is an array with 3 elements, it will run once for each element, once for the length property, and once each for... whatever the other two built-in properties are. That's six times total, which is probably not what you want. Use for(var i=0;i<elems.length;i++) for reliability.

Rex M
Thank you, I forgot to increment my cntr.
James Black