1. 程式人生 > >JS與jQuery繫結事件的寫法

JS與jQuery繫結事件的寫法

js

1.直接在html標籤中繫結

在html標籤中新增“on”+事件名稱的屬性來繫結事件

<button type="button" id="btn" onclick="alert(1)">點選</button>

2.在DOM元素上繫結

DOM元素新增‘on’+事件名稱的屬性,this指向的是當前的DOM物件

document.getElementById('btn').onclick = function(){
    alert(1);
}

3.通過函式呼叫

將事件另寫成個函式,元素只需呼叫該函式

<button type="button" id="btn" onclick="foo()">點選</button>

function foo(){
    alert(1);
}

jQuery

1.

$("#btn").click(function(){
    alert(1);
})

2.jQuery的on繫結事件

$('#btn').on('click',function(){
    alert(1);
})