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

猜你喜欢

转载自blog.csdn.net/weixin_42217154/article/details/84965018
今日推荐