views:

27

answers:

1

Hi, I have a script where Im trying to add an eventlistener to a link, and it watches for when a user clicks the link. when the link gets clicked it calls the function 'hi'. im having trouble because the function 'hi' gets called even when the link isnt clicked. same result on IE and FF. heres my code maybe someone can help:

function hi(id) {   
var xmlhttp = new XMLHttpRequest();
urlwat = "wat.php?id="+id;
xmlhttp.open("POST",urlwat,true);
xmlhttp.send(null);
}

function wat1() {
    object1 = document.getElementById("watlol");
    try {
      object1.attachEvent("click",hi(9));
    }
    catch(e) {
      object1.addEventListener("click",hi(9),false);
    }
}
window.onload = wat1;
+5  A: 

You're calling the hi function itself within the attachEvent and addEventListener calls. Change it to be:

function wat1() {
    object1 = document.getElementById("watlol");
    try {
      object1.attachEvent("click", function() { hi(9); });
    }
    catch(e) {
      object1.addEventListener("click",function() { hi(9); },false);
    }
}

The parameter expects a reference to a function, whereas passing it hi(9) is passing the result of calling the function hi

zincorp