search
HomeWeb Front-endJS TutorialGive you an in-depth understanding of the Bind() function in JQuery

Give you an in-depth understanding of the Bind() function in JQuery

Jun 25, 2017 am 11:03 AM
bindjqueryeventanalyzeusage

This article mainly introduces the usage of Bind() event in JQuery. It analyzes the function, characteristics and usage skills of Bind() event with examples. Friends in need can refer to this article

The example analyzes the usage of Bind() event in JQuery. Share it with everyone for your reference. The specific analysis is as follows:

Let’s take a look at its definition first:


.bind( eventType [, eventData], handler(eventObject))

. The main function of the Bind() method is to bind the object to it The above provides some behavior of event methods. The meanings of its three parameters are as follows:

eventType is a string type event type, which is the event you need to bind. Such types can include the following: blur, focus, focusin, focusout, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress , keyup, error. What needs to be noted here is that the event methods in JavaScript are used here, not in JQuery. The event methods in JQuery all have an extra "on" in front of JavaScript, such as onclick, onblur, etc.

The eventData parameter is an optional parameter, but it is rarely used in normal times. If this parameter is provided, then we can pass some additional information to the Event handling function. This parameter has a good use, which is to deal with problems caused by closures. I will give you an example later.

Handler is the processing number used for binding, which is actually the callback function, the corresponding method after processing the data.

1. The first simple bind () event---Hello Word


<input id="BtnFirst"type="button"value="Click Me"/>
<script>
$(function () {
 $("#BtnFirst").bind("click",function(){
  alert("Hello World");
 });
})
</script>

After opening the page, click the button "Click Me", "Hello World" will pop up. This is our simplest binding event. It's very simple.

2. Bind multiple events

We can bind multiple events through bind() (in fact, this is also a very famous event in JQuery and Linq Chain programming). The main function implemented is that when we click, "Hello World" pops up, and when we leave the button, a p is displayed.


<p>
<input id="BtnFirst"type="button"value="Click Me"/></p>
<p id="Testp"style=" width:200px; height:200px; display:none; ">
</p>
<script>
$(function () {
 $("#BtnFirst").bind("click", function () {
  alert("Hello World");
 }).bind("mouseout", function () {
  $("#Testp").show("slow");
 });
})
</script>

This code page is easy to understand. When the button is clicked, a "Hello World" will pop up. When leaving, the p will be displayed. . For animations in JQuery, you can use "slow", "fast" and "normal". Of course, you can also set the relevant milliseconds.

3.bind() event object

Handler callback function can accept a parameter, when this function is called, a JavaScript event object will be passed in as a parameter.

Give me an example from the JQuery official website:


<style> 
 p {background:yellow;font-weight:bold;cursor:pointer;3 padding:5px;}
 p.over {background:#ccc;}
 span {color:red;}
</style>
<p>Click or double click here.</p>
<span></span>
<script>
 $("p").bind("click", function(event){
  var str = "( " + event.pageX + ", " + event.pageY + " )";
  $("span").text("Click happened! " + str);
 });
 $("p").bind("dblclick", function(){
  $("span").text("Double-click happened in " + this.nodeName);
 });
 $("p").bind("mouseenter mouseleave", function(event){
  $(this).toggleClass("over");
 });
</script>

The main function here is to realize that when the user clicks on the p object, the current relative to The coordinates of the page are displayed in the span tag, and the event event is used here. Pass the parameters in.

4.unbind() event

unbind([type],[data],Handler) is the reverse operation of bind(), starting from each matching Remove the bound event from the element. If there are no parameters, all bound events are deleted. You can unbind custom events you registered with bind(). If an event type is provided as a parameter, only bound events of that type are removed. If a handler is passed as the second argument when binding, only that specific event handler will be removed.


<body onclick="MyBodyClick()">
 <p onclick="MyClickOut()">
  <p onclick="MyClickInner()">
   <span id="MySpan">I love JQuery!! </span>
  </p>
 </p>
 <span id="LooseFocus">失去焦点</span>
</body>
<script>
function MyClickOut() {
 alert("outer p");
}
function MyClickInner() {
 alert("Inner p");
}
function MyBodyClick() {
 alert("Body Click");
}
var foo = function () {
 alert("I&#39;m span.");
}
$(function () {
 $("#MySpan").bind("click", foo);
})  
$(function () {
 $("#LooseFocus").unbind("click", foo);
})
</script>

The above code is also easy to understand. When the user's mouse stays on the span, the click event of the span is then cancelled. So, in the end it will only pop up the alert inside the body.

Finally, let’s briefly understand the use of one() event. In fact, one and bind are the same, both are generated for binding events. One is basically the same as bind. The difference is that when calling jQuery.event.add, the registered event processing function is slightly adjusted. One called jQuery.event.proxy to proxy the incoming event processing function. When an event triggers a call to this agent's function, the event is first deleted from the cache, and then the registered event function is executed. Here is the application of closure, through which the reference of the event function registered by fn is obtained.

Usage rules:


one(type,[data],fn)

Bind a one-time event handler function for each specific event (like click) of the matching element. This event handler is executed only once on each object. Other rules are the same as bind() function. This event handler will receive an event object, which can be used to prevent the default behavior. If you want to cancel the default behavior and prevent the event from bubbling, the event handler must return false.

Post it, the implementation of the respective codes of bind and one, the reader can make a slight comparison:

The implementation of the Bind() code:


bind : function(type, data, fn) { 
 return type == "unload" ? this.one(type,data,fn) : this.each(function(){
 //fn || data, fn && data实现了data参数可有可无 
  jQuery.event.add(this, type, fn || data, fn && data); 
 }); 
}

Implementation of One() code:


one : function(type, data, fn) { 
 var one = jQuery.event.proxy(fn || data, function(event) { 
  jQuery(this).unbind(event, one); 
  return (fn || data).apply(this, arguments);
 //this->当前的元素 
 }); 
 return this.each(function() { 
  jQuery.event.add(this, type, one, fn && data); 
 }); 
}

5.最后呢,其实想在贴一个冒泡事件,因为在处理绑定事件的时候,如果调用内部的事件 有可能会触发外面的事件,所以给大伙一个借鉴吧。

这里可以参考一下javascript事件冒泡的文章:《JavaScript 事件冒泡简介及应用》。

简单的说,何为冒泡事件?其实,简单的理解是,也可以说是事件传播,它会从内部的控件广播到父类的元素,然后接着一直往上到祖先级别的元素。

则 冒泡实例代码:


<body onclick="MyBodyClick()">
 <p onclick="MyClickOut()">
  <p onclick="MyClickInner()">
    <span id="MySpan">
     I love JQuery!!
    </span>
  </p>
 </p>
</body>
<script type="text/javascript">
 function MyClickOut() {
  alert("outer p");
 }
 function MyClickInner() {
  alert("Inner p");
 }
 function MyBodyClick() {    
  alert("Body Click");
 }
 $(function () {
  $("#MySpan").bind("click", function (event) {
   alert("I&#39;m span");
   event.stopPropagation();
 });
</script>

The above is the detailed content of Give you an in-depth understanding of the Bind() function in JQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.