在元素上添加事件监听器 - Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6445207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:45:40  来源:igfitidea点击:

Adding Event Listeners on Elements - Javascript

javascriptdomelementevent-listener

提问by simplified.

Are there ways for me to listen for onblur or onclick events in javascript from an onload function? instead of doing it in the element itself.

有没有办法让我从 onload 函数中监听 javascript 中的 onblur 或 onclick 事件?而不是在元素本身中进行。

<input type="button" id="buttonid" value="click" onclick="func()">

to become something like

变得像

function onload() {
      var button = document.getElementById("buttonid");
      button.addEventListener("onclick", function() { alert("alert");});
}

EDIT

编辑

<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>

UPDATE

更新

 <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>

回答by Shef

The way you are doing it is fine, but your event listener for the clickevent should be like this:

你这样做的方式很好,但你的事件监听器click应该是这样的:

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

Notice, the clickevent should be attached with "click", not "onclick".

请注意,click事件应附加"click",而不是"onclick"

You can also try doing this the old way:

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

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

Update 1

更新 1

You need to also monitor for IE < 9, because those Vs use attachEvent(). Attach the event like this, so it will work with dinosaur browsers:

您还需要监视 IE < 9,因为那些 Vs 使用attachEvent(). 像这样附加事件,以便它可以与恐龙浏览器一起使用:

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

Update 2

更新 2

Based on your edit, this should workworks just fine.

根据您的编辑,这应该可以正常工作

<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>

Please, do not use window.onload = on_load();, this will prevent all other onloadevent listeners from getting fired, or you are risking for your event listener to get overwritten. Consider attaching the onloadevent the way I am suggesting above.

请不要使用window.onload = on_load();,这将防止所有其他onload事件侦听器被触发,否则您的事件侦听器可能会被覆盖。考虑onload按照我上面建议的方式附加事件。

回答by Jerzy Dro?d?

The better way it's used DOM (works perfectly) like this. Firs write Yours function/class and use it in:

像这样使用 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>

It's doesn't matter where You used this few lines. You can put it in head or in body.

你在哪里使用这几行并不重要。你可以把它放在头上或身体里。

回答by FishBasketGordo

A better way to dynamically add event handlers would be to use a JavaScript library like jQuery, because it will abstract away any browser-specific details.

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

回答by thescientist

to further my conversation in the comments section...

在评论部分进一步我的谈话......

@simplified, try putting this in the < head > of your page

@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>

and see what happens. also, please advise us on which browser you are using. https://developer.mozilla.org/en/DOM/element.addEventListener

看看会发生什么。另外,请告知我们您使用的浏览器。 https://developer.mozilla.org/en/DOM/element.addEventListener

回答by Waheed Rahman

<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>