javascript附加事件 [英] javascript attaching events

查看:109
本文介绍了javascript附加事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到你可以附加这样的事件

I've seen that you can attach events like this

<button type="button" id="myButton" onclick="myFunction()">

如果没有onclick =,如:

document.getElementById('myButton'). //and here attach the event on click to myFunction

我试图保持JavaScript和HTML分开

I'm trying to keep JavaScript and HTML separate.

推荐答案

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

It's similar to the onclick approach, and in fact uses the same event-handler, but is removed from the HTML:

document.getElementById('myButton').onclick = function(){
    // do stuff
    myFunction();
}

如果您没有 id 你可以使用的元素:

If you don't have an id on the element you could also use:

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();
        };
    }
}

另一种方法是使用 Array.prototype.forEach(),使用 Array.prototype.slice()文档创建的元素数组.querySelectorAll()

An alternative approach, using Array.prototype.forEach(), with an array of elements created using Array.prototype.slice() and document.querySelectorAll():

[].forEach.call(document.querySelector('input[type="text"]', yourFunctionName);

这将执行 $ code> type =text的每个< input /> 元素的yourFunctionName() $ c>,由 document.querySelectorAll()返回,将< input /> 元素传递到函数中这个

This will execute the yourFunctionName() function for each <input /> element, of type="text", returned by document.querySelectorAll() passing that <input /> element into the function as this.

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

You could also use addEventListener() in this case:

document.getElementById('myButton').addEventListener('click', myFunction, false);

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

And also in this situation, using document.querySelector() (as opposed to document.querySelectorAll()), which returns the first element that matches the passed-in selector, using CSS notation:

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

或:

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

参考文献:

  • Array.prototype.forEach().
  • Array.prototype.slice().
  • document.querySelector().
  • document.querySelectorAll().
  • EventTarget.addEventListener().

这篇关于javascript附加事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆