Implementations of multiple jQuery binding events
- 2021-06-28 10:32:00
- OfStack
It has recently been found that events for jQuery1 objects can be bound repeatedly, causing code to execute multiple times when the event is triggered.
Below is an example of an click event being duplicated bound:
function reg_button_click(){
$("#button).click(function(){
alert("button click");
});
}
$(document).ready(function(){
# Duplicate registration 3 second
reg_button_click();
reg_button_click();
reg_button_click();
# When triggered Appear 3 individual alert
$('#button').click();
});
The following solutions are given:
For scenarios where duplicate binding is required, consider using the unbind and bind method for event registration.Or off before on
function reg_button_click(){
$("#button).unbind('click').bind('click',(function(){
alert("button click");
});
}
$(document).ready(function(){
# Duplicate registration 3 second
reg_button_click();
reg_button_click();
reg_button_click();
# When triggered Appear 3 individual alert
$('#button').click();
});
What is the implementation of the jQuery binding event? Here is how to share the jQuery binding event for your reference. The details are as follows
<html>
<head>
<meta charset="utf-8" />
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script><!-- Baidu CDN-->
</head>
<body>
<input type="text"/>
<input type="button" value="button1"/>
<script>
$(function(){
var text = $(":text");
var button = $(":button");
// Debugger Logging console.log("message"); For example: Firefox Browser, open FireBug( Press F12)
// Trigger a single event: two ways
button.bind("mouseover",function(){
console.log(" Move in ");
});
button.bind({
"mouseout": function(){
console.log(" Move Out ");
}
});
// Multiple events: 3 Ways
text.bind("dblclick blur",function(){
console.log(" Double-click or lose focus ");
});
text.bind({
"dblclick blur":function(){
console.log(" Double-click or lose focus ");
}
});
text.bind({
"dblclick":function(){
console.log(" double-click ");
},
blur:function(){
console.log(" Lose focus ");
}
});
// Cancel event
text.unbind("dblclick"); // Cancel single event
//text.unbind("dblclick blur"); // Cancel multiple events
//text.unbind(); // Cancel all events
});
</script>
</body>
</html>
This is the whole content of this article, and I hope it will be helpful for you to learn jQuery program design.