javascript附加事件

use*_*124 4 javascript events handler

我见过你可以附上这样的事件

<button type="button" id="myButton" onclick="myFunction()">
Run Code Online (Sandbox Code Playgroud)

如果没有"onclick=",你可以这样做,如:

document.getElementById('myButton'). //and here attach the event on click to myFunction
Run Code Online (Sandbox Code Playgroud)

我试图将JavaScript和HTML分开.

Dav*_*mas 8

它与onclick方法类似,实际上使用相同的事件处理程序,但是从HTML中删除:

document.getElementById('myButton').onclick = function(){
    // do stuff
    myFunction();
}
Run Code Online (Sandbox Code Playgroud)

如果你没有id元素,你也可以使用:

var inputs = document.getElementsByTagName('input');

for (var i=0, len=inputs.length; i<len; i++){
    if (inputs[i].type == 'text'){
        // assuming you want to affect text-inputs in this case
        inputs[i].onclick = function(){
            // do stuff. In here 'this' refers to inputs[i] element
            myFunction();
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法,使用Array.prototype.forEach()和使用Array.prototype.slice()和创建的元素数组document.querySelectorAll():

[].forEach.call(document.querySelector('input[type="text"]', yourFunctionName);
Run Code Online (Sandbox Code Playgroud)

这将通过将该元素传递给函数而返回的yourFunctionName()每个<input />元素执行函数.type="text"document.querySelectorAll()<input />this

您也可以addEventListener()在这种情况下使用:

document.getElementById('myButton').addEventListener('click', myFunction, false);
Run Code Online (Sandbox Code Playgroud)

而且在这种情况下,使用document.querySelector()(而不是document.querySelectorAll()),使用CSS表示法返回与传入选择器匹配的第一个元素:

// gets the element with an 'id' of 'myButton', binding the 'click' event-handler:
document.querySelector('#myButton').addEventListener('click', myFunction, false);
Run Code Online (Sandbox Code Playgroud)

要么:

// gets the first of the <input> elements, binding the 'click' event-handler:
document.querySelector('input').addEventListener('click', myFunction, false);
Run Code Online (Sandbox Code Playgroud)

参考文献: