Introduction to several methods of binding click events to

黄舟
Release: 2017-07-27 14:09:18
Original
38349 people have browsed it

There are three ways to bind events to buttons in HTML.

For example, the following tags:

<button type="submit" id="btn_submit"> submit </button>
Copy after login

1. Use jquery for binding

$(&#39;#btn_submit&#39;).click(function(){
});
Copy after login

2. Use native js binding, (Note: Internet Explorer 8 and earlier IE versions do not support the addEventListener() method, and Opera 7.0 and Opera earlier versions do not support it either. This type of The browser version needs to use the attachEvent() method to add events)

document.getElementById("#btn_submit").addEventListener(‘click’, function(){
}, false);
Copy after login

Supplement: The third step of addEventListener This parameter is used to determine the event model. When both the parent element and the child element are bound to the event, this parameter determines which event is triggered first. False is the bubbling event model: that is, the event bound to the child element responds first, and the event bound to the parent element responds first. After responding to a certain event, true asks the capture event model, which is opposite to the execution order of the bubbling event model, such as:

<p id="test_p">   
<button type="button" value ="测试事件顺序" name="测试事件顺序" id="test_button">测试事件顺序</button></p>
document.getElementById(&#39;test_p&#39;).addEventListener(&#39;click&#39;, function () {        
console.log(&#39;p&#39;);    
},true)    
document.getElementById(&#39;test_button&#39;).addEventListener(&#39;click&#39;, function(){        
console.log(&#39;test1&#39;);    
},false);
Copy after login

The event model in this example is a capture model, and it will be executed first Execute p's event and then execute button's event. There is something to note here: what determines the event model is the third parameter passed when the parent element binds the event, such as the third parameter passed when the button binds the event in the above example. has no effect unless it contains child elements.

3. Use onclick binding directly in the button tag

<button type="submit" id="btn_submit" onclick="btnAction()"> submit </button>
Copy after login

Then define btnAtion in the

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!