Html 使用纯 JavaScript 处理“onclick”事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17633152/
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-29 11:05:33  来源:igfitidea点击:

Handling "onclick" event with pure JavaScript

javascripthtmleventsjavascript-eventsevent-handling

提问by April_Nara

So this is really straight forward but I'm still fairly new to JavaScript and just found JSFiddle. I'm trying to find the element with the getElementById()to disable and enable a button. What am I missing?

所以这真的很简单,但我对 JavaScript 还是很陌生,刚刚发现了 JSFiddle。我试图找到带有getElementById()禁用和启用按钮的元素。我错过了什么?

<form name="frm" > 
  <div id="chkObj"> 
    <input type="checkbox" name="setChkBx" onclick="basicList.modifyAndEnableButton(this)"></input>        
</div>
<div id="Hello"> 
    <input type="button" name="btn" value="Hello"></input>        
</div>


This is a list that I am using to add checkboxes because there is going to be more than one:


这是我用来添加复选框的列表,因为将有多个:

 var basicList = {
    'items': {},
    'modifyAndEnableButton': function(obj1) {
        var element = document.getElementsByName("btn");
        if (obj1.checked == true && element.getAttribute('disabled') == false) {
            element.getAttribute('disabled') = true;
            this.addRecord(obj2);
        } else if (element.getAttribute('disabled') == true) {
            if (hasItems == false) {
                element.getAttribute('disabled') = false;
            }
        } 
    }
};

http://jsfiddle.net/Arandolph0/E9zvc/3/

http://jsfiddle.net/Arandolph0/E9zvc/3/

Thanks in advance for your help.

在此先感谢您的帮助。

回答by Benjamin Gruenbaum

All browsers support this (see example here):

所有浏览器都支持这个(见这里的例子)

mySelectedElement.onclick = function(e){
    //your handler here
}

However, sometimes you want to add a handler (and not change the same one), and more generally when available you should use addEventListener(needs shim for IE8-)

但是,有时您想添加一个处理程序(而不是更改相同的处理程序),并且更一般地在可用时您应该使用addEventListener(需要 IE8- 的垫片)

mySelectedElement.addEventListener("click",function(e){
   //your handler here
},false);

Here is a working example:

这是一个工作示例:

var button = document.getElementById("myButton");
button.addEventListener("click",function(e){
    button.disabled = "true";
},false);

And html:

和 html:

<button id='myButton'>Hello</button>

(fiddle)

(小提琴)

Here are some useful resources:

以下是一些有用的资源:

回答by Atif Mohammed Ameenuddin

Benjamin's answer covers quite everything. However you need a delegation model to handle events on elements that were added dynamically then

本杰明的回答涵盖了一切。但是,您需要一个委托模型来处理动态添加的元素上的事件

document.addEventListener("click", function (e) {
    if (e.target.id == "abc") {
        alert("Clicked");
    }
});

For IE7/IE8

对于 IE7/IE8

document.attachEvent('onclick', function (e) {
    if (window.event.srcElement == "abc") {
        alert("Clicked");
    }
});

回答by iConnor

You have a Errorhere

你有一个Error在这里

btnRushshould be Rushbtn

btnRush应该 Rushbtn

This is a example of cross browser event's I just made (not tested) )

这是我刚刚制作的跨浏览器事件的示例(未测试))

var addEvent = function( element, type, callback, bubble ) { // 1
    if(document.addEventListener) { // 2
        return element.addEventListener( type, callback, bubble || false ); // 3
    }
    return element.attachEvent('on' + type, callback ); // 4
};



var onEvent = function( element, type, callback, bubble) { // 1
    if(document.addEventListener) { // 2
        document.addEventListener( type, function( event ){ // 3
            if(event.target === element || event.target.id === element) { // 5
                callback.apply(event.target, [event]); // 6
            }
        }, bubble || false);
    } else {
        document.attachEvent( 'on' + type, function( event ){ // 4 
            if(event.srcElement === element || event.srcElement.id === element) { // 5
                callback.apply(event.target, [event]); // 6
            }
        });
    }

};

Steps

脚步

  1. Create a function that accepts 4 values ( self explaining )
  2. Check if the browser supports addEventListener
  3. Add event on the element
  4. else add event on the element for older IE
  5. Check that the (clicked) element is = to the passed element
  6. call the callback function pass the element as this and pass the event

    The onEventis used for event delegation. The addEventis for your standard event.

    here's how you can use them

  1. 创建一个接受 4 个值的函数(自我解释)
  2. 检查浏览器是否支持 addEventListener
  3. 在元素上添加事件
  4. 否则在旧 IE 的元素上添加事件
  5. 检查(单击的)元素是否为 = 传递的元素
  6. 调用回调函数将元素作为 this 传递并传递事件

    onEvent用于事件委派。这addEvent是为您的标准事件。

    这是您如何使用它们

The first 2 are for dynamically added elements

前 2 个用于动态添加的元素

onEvent('rushBtn', 'click', function(){
    alert('click')
});

var rush = document.getElementById('rushBtn');

onEvent(rush, 'click', function(){
    alert('click');
});

// Standard Event
addEvent(rush, 'click', function(){
    alert('click');
});

Event Delegation is this basically.

事件委托基本上就是这样。

Add a click event to the document so the event will fire whenever & wherever then you check the element that was clicked on to see if it matches the element you need. this way it will always work.

向文档添加一个点击事件,这样该事件就会随时随地触发,然后您检查被点击的元素以查看它是否与您需要的元素匹配。这样它就会一直有效。

Demo

演示