简体   繁体   English

javascript eventlistener问题

[英]javascript eventlistener problem

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'. 当链接被点击时,它将调用函数“ hi”。 im having trouble because the function 'hi' gets called even when the link isnt clicked. 我有麻烦,因为即使没有单击链接,也会调用函数“ hi”。 same result on IE and FF. IE和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. 您正在在attachEvent和addEventListener调用中调用hi函数本身。 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 该参数期望对函数的引用 ,而传递给hi(9)则传递调用函数hi的结果

One more method of doing same is function wat1() { 执行此操作的另一种方法是function wat1(){

object1 = document.getElementById("watlol");

try 
 {

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

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

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