Home >Web Front-end >JS Tutorial >Analysis of Bind() event usage in JQuery_jquery

Analysis of Bind() event usage in JQuery_jquery

WBOY
WBOYOriginal
2016-05-16 16:01:011110browse

This article analyzes the usage of Bind() event in JQuery with examples. 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 provide some event method behaviors on the object bound to it. The meanings of its three parameters in the term 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 handler function. This parameter has a very 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. In fact, it is also 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" and "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 the very famous chain programming in JQuery and Linq). The main function implemented is that when we click, "Hello World" pops up, and when we leave the button, a div is displayed.

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

This code page is easy to understand. When the button is clicked, a "Hello World" pops up, and when you leave, the div is 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.

This event object is usually a parameter that is not necessary and can be omitted, because when the event handler function is bound, you can clearly know what it should do when it is triggered, and usually sufficient information can be obtained. Sometimes, however, it is necessary to obtain more information about the user's environment during event initialization.

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 display the current coordinates relative to the page in the span tag when the user clicks on the p object. The event event is used here. Pass the parameters in.

4.unbind() event

unbind([type],[data],Handler) is the reverse operation of bind() and removes the bound event from each matching 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()">
 <div onclick="MyClickOut()">
  <div onclick="MyClickInner()">
   <span id="MySpan">I love JQuery!! </span>
  </div>
 </div>
 <span id="LooseFocus">失去焦点</span>
</body>
<script>
function MyClickOut() {
 alert("outer Div");
}
function MyClickInner() {
 alert("Inner Div");
}
function MyBodyClick() {
 alert("Body Click");
}
var foo = function () {
 alert("I'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 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 to a specific event (like click) for each matched 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 the implementation of the respective codes of bind and one. The reader can make a slight comparison:

Bind() code implementation:

bind : function(type, data, fn) { 
 return type == "unload" &#63; 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()">
 <div onclick="MyClickOut()">
  <div onclick="MyClickInner()">
    <span id="MySpan">
     I love JQuery!!
    </span>
  </div>
 </div>
</body>
<script type="text/javascript">
 function MyClickOut() {
  alert("outer Div");
 }
 function MyClickInner() {
  alert("Inner Div");
 }
 function MyBodyClick() {    
  alert("Body Click");
 }
 $(function () {
  $("#MySpan").bind("click", function (event) {
   alert("I'm span");
   event.stopPropagation();
 });
</script>

希望本文所述对大家的jQuery程序设计有所帮助。

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