12

JS三个事件绑定方法

 4 years ago
source link: http://www.cnblogs.com/itmacy/p/12588966.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

1. JS三个事件绑定方法

1.1. 使用html进行事件绑定

1.直接在html标签上写入事件类型和事件处理方法。

<button onclick = "alert('hello world')">click me!</button>

2.在html标签上写入事件类型,在js上写事件处理方法。

  • html部分
<button onclick = "sayHello()">click me!</button>
  • js部分
function sayHello(){
  alert('hello world!!!')
}

1.2. 使用JS获取dom对象进行事件绑定

为了让代码更加整洁以及便于维护,使html代码与js代码解耦。

  • html部分
<button id="btn">click me!</button>
  • js部分

    注意在调用事件方法时,不要加上括号,否则会立即调用,之后点击按钮就没反应了。

document.querySelector('#btn').onclick = sayHello

function sayHello() {
  alert('hello world')
}

1.3. 使用addEventListener()绑定事件

使用上面两种方法,只能绑定一个事件,如果要绑定多个事件,可以使用 addEventListener() 添加事件监听器,一般情况下传入两个参数,第一个参数是事件类型,第二个参数是事件处理方法。

  • html部分
<button id="btn">click me!</button>
  • js部分

    注意在写入事件类型时,不要加上 on

document.querySelector('#btn').addEventListener('click',sayHello)
document.querySelector('#btn').addEventListener('click',sayHi)

function sayHello() {
  alert('hello world!')
}
function sayHi () {
  alert('hi!')
}

小结:

addEventListener()

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK