为元素添加事件监听器 - Javascript

17
有没有办法在javascript的onload函数中监听onblur或onclick事件,而不是在元素本身中执行?
<input type="button" id="buttonid" value="click" onclick="func()">

成为类似于某物
function onload() {
      var button = document.getElementById("buttonid");
      button.addEventListener("onclick", function() { alert("alert");});
}

编辑

<html>

<head>

     <script>

     function onload() {

        var button = document.getElementById("buttonid");

        if(button.addEventListener){
             button.addEventListener("click", function() { alert("alert");});
        } else {
             button.attachEvent("click", function() { alert("alert");});
        };
     };

          window.onload = onload;


     </script>

</head>

<body>

<input type="button" id="buttonid" value="click">


</body>

</html>

更新

 <script type="text/javascript">

 function on_load() {

    var button = document.getElementById("buttonid");

    if(button.addEventListener){
         button.addEventListener("click", function() { alert("alert");});
    } else {
         button.attachEvent("click", function() { alert("alert");});
    };
 };

      window.onload = on_load();


 </script>


1
如果你的意思是 _window.onload = onload_,那么这个方法可以使用,或者类似的方法也可以。你试过你的例子看看会发生什么吗? - thescientist
@thescientist,对我来说实际上并没有起作用,也许我在某个地方出现了一些错误。 - simplified.
@thescientist 我已经尝试将 onclick 更改为 click,但仍然无法工作。让我查看错误控制台并查看它说了什么。谢谢。 - simplified.
另一个重要的注意事项是,你如何调用onload?我建议将它分配为window.onload,以确保在引用该函数之前DOM已准备就绪。你这样做了吗? - thescientist
你忘记在开头的 script 标签中添加 type="text/javascript" 了。 - thescientist
显示剩余17条评论
5个回答

18

你目前的方法是可行的,但是 click 事件的监听器应该像这样:

button.addEventListener("click", function() { alert("alert");});

请注意,应该使用"click"而不是"onclick"来附加click事件。

您也可以尝试以传统方式执行此操作:

function onload() {
   var button = document.getElementById("buttonid");
   // add onclick event 
   button.onclick = function() { 
        alert("alert");
   }
}

更新1

你还需要监测IE < 9,因为这些版本使用 attachEvent()。像这样附加事件,这样它就可以在旧版浏览器中正常工作:

if(button.addEventListener){
    button.addEventListener('click', function() { alert("alert");});    
} else if(button.attachEvent){ // IE < 9 :(
    button.attachEvent('onclick', function() { alert("alert");});
}

更新2

根据你的编辑,这个应该可以工作完全正常工作

<html>
    <head>
        <script type="text/javascript">
            function init() {
                var button = document.getElementById("buttonid");
                if(button.addEventListener){
                    button.addEventListener("click", function() { alert("alert");}, false);
                } else if(button.attachEvent){
                    button.attachEvent("onclick", function() { alert("alert");});
                }
            };
            if(window.addEventListener){
                window.addEventListener("load", init, false);
            } else if(window.attachEvent){
                window.attachEvent("onload", init);
            } else{
               document.addEventListener("load", init, false);
            }
        </script>
    </head>
    <body>
        <input type="button" id="buttonid" value="click">
    </body>
</html>
请不要使用window.onload = on_load();,这将防止所有其他onload事件监听器被触发,或者你会冒着你的事件监听器被覆盖的风险。请考虑按照我上面建议的方法来附加onload事件。

谢谢您的回复,我尝试更改添加事件监听器的方式,但似乎仍然无法正常工作。我可能漏掉了什么吗? - simplified.
我尝试用你提供的onload方法替换整个代码,还尝试将"onclick"替换为"click",但它似乎仍然无法正常工作。我也没有看到任何错误,你知道可能的原因吗? - simplified.
如果您在使用IE浏览器版本小于9的情况下查看,请检查是否更新。另一个可能导致其不起作用的原因是,您没有在body标签上调用onload()函数,如<body onload="onload()"> - Shef
1
“旧”的方式比使用事件监听器更稳定。这种方式没有任何问题。事件监听器很方便,但对于基本的DOM脚本来说是不必要的。 - user1385191
@Matt McDonald:我同意。实际上,这就是我最初建议的内容。对于一些琐碎的事情,我经常将它们连接起来,这就是为什么它是我首先想到的东西。 :) - Shef

2
更好的方法是使用DOM(完美地工作),像这样:
首先编写您的函数/类并在其中使用它:

document.addEventListener('DOMContentLoaded', function(){
  // put here code
});
<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
    function myFunc(){ alert('Hellow there!'); }
    
    document.addEventListener('DOMContentLoaded', function(){
        document.getElementById('mybtn').addEventListener('click', myFunc);
    });
  </script>
</head>
  <body>
    <button id="mybtn">Cklik!</button>
  </body>
</html>

无论您将这几行代码放在哪里都没有关系。您可以将其放在标签中或标签中。


0

为了在评论区进一步交流...

@simplified,尝试将这个放在你页面的 < head > 中

<script type="text/javascript">
function my_onload() {
  var button = document.getElementById("buttonid");
  if(button.addEventListener){
    button.addEventListener("click", function() { alert("alert");}, true);
  }else{
    button.attachEvent("click", function() { alert("alert");});
  };
};
window.onload = my_onload;
</script>

试试看会发生什么。另外,请告诉我们您使用的浏览器。 https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener


@thescientist,我在上一条评论部分提到了,我正在使用Mozilla Firefox浏览器。不太确定版本号。无论如何,OP是什么意思? - simplified.
@thescientist 哦,原来是这个意思。问题在于我尝试替换HTML头部中整个脚本标签,但它仍然无法正常工作。它仍然会抛出“太多递归”错误,而我不知道为什么。 - simplified.
你确定你只有一个带有那个ID的元素吗?能否更新您的原始帖子,包括整个代码?仅使用基本标记(仅限HTML / head / body标记),脚本和按钮元素? - thescientist
@thescientist 是的,我非常确定那是唯一一个具有该ID的元素,因为整个HTML页面中只有1个元素。 - simplified.
很棒,我已经在你的原始帖子中添加了解决方案。如果它有效(应该是的,哈哈),请随意接受我的答案!;) - thescientist
显示剩余4条评论

0
<script>
var click = document.getElementById("click");
click.addEventListener("click", function() {
  var required = document.getElementById("required").value;
  if (required===null || required==="") {
    alert("Please make sure all required field are completed");
  }
  else  {
    alert("Thank you! \nYour sumbission has been accepted and you will receive a conformation email shortly! \nYou will now be taken to the Home page.");
  }
});
</script><html>
<body>
<div id="popup">
    <textarea cols="30" rows="2" name="required" id="required"></textarea>
    <input type="submit" id="click" value="Submit">
           <input type="reset" value="Reset" />
</div>
</body>
</html>

0
更好的动态添加事件处理程序的方法是使用像jQuery这样的JavaScript库,因为它会抽象掉任何特定于浏览器的细节。

@FishBasketGordo,谢谢你的回复,你介意解释一下“浏览器特定细节”的含义吗? - simplified.
@FishBasketGordo 哦,这是否意味着如果我决定不使用jQuery,为了使代码兼容大多数浏览器,我必须编写if else来检查? - simplified.
@FishBasketGordo 因为问题在于我只会使用它提供的1或2个函数,实际上包含其余部分是否多余? - simplified.
我之前听过这个问题。jQuery非常轻量级。压缩后的jQuery只有31KB,如果你愿意,你可以链接到谷歌极快的服务器上(http://code.google.com/apis/libraries/devguide.html#jquery)。在大多数情况下,它不会明显影响性能。 - FishBasketGordo
@FishBasketGordo 是的,我也看过相关内容,有人提出了具体问题。但我实际上想知道不同的方法来做到这一点。因为我并不是真的依赖它来让事情正常运转。不过还是谢谢你的解释。 - simplified.
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接