开发者

javascript eventlistener problem

开发者_JAVA技巧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;


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


One more method of doing same is function wat1() {

object1 = document.getElementById("watlol");

try 
 {

  object1.onclick  = function() 
   {
                                 hi(9);
   };
}
catch(e) 
 {
  object1.onclick  = function() 
   {
                                 hi(9);
    };
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜