jQuery如何使用bind()方法?代码示例

2021年3月28日16:16:40 发表评论 943 次浏览

bind()是jQuery中的内置方法, 用于为所选元素附加一个或多个事件处理程序, 并且此方法指定事件发生时要运行的函数。

语法如下:

$(selector).bind(event, data, function);

参数:它接受下面指定的三个参数-

  1. 事件:这是事件类型, 将传递给所选元素。
  2. 数据:这是可以在所选元素上显示的数据。
  3. 功能:这是由所选元素执行的功能。

返回值:它返回对选定元素所做的所有修改。

jQuery代码显示bind()方法的工作方式:

代码1:

在下面的代码中, 使用此方法将" click"事件附加到给定的段落中。

< html >
  
< head >
     < script src="https://ajax.googleapis.com/ajax/libs/
               jquery/3.3.1/jquery.min.js"></ script >
     < script >
         $(document).ready(function() {
             $("p").bind("click", function() {
                 alert("Given paragraph was clicked.");
             });
         });
     </ script >
     < style >
         p {
             display: block;
             padding: 50px;
             width: 280px;
             border: 2px solid green;
         }
     </ style >
</ head >
  
< body >
     < p >Click me!</ p >
</ body >
  
</ html >

输出如下:

在点击"点击我"框之前,

jQuery如何使用bind()方法?代码示例1

点击"点击我"框后,

jQuery如何使用bind()方法?代码示例2

代码2:

在下面的代码中, 添加了相同的" click"事件, 但是这次数据也传递给了该方法。

< html >
  
< head >
     < script src="https://ajax.googleapis.com/ajax/libs/
           jquery/3.3.1/jquery.min.js"></ script >
     < script >
         function handlerName(e) {
             alert(e.data.msg);
         }
         <!--Here data is passing along with a function in
              bind method-->
         $(document).ready(function() {
             $("p").bind("click", {
                 msg: "You just clicked the paragraph!"
             }, handlerName)
         });
     </ script >
     < style >
         p {
             display: block;
             padding: 50px;
             width: 280px;
             border: 2px solid green;
         }
     </ style >
</ head >
  
< body >
     <!--A pop will appear after clicking on this paragraph-->
     < p >Click me!</ p >
</ body >
  
</ html >

输出如下:

在点击"点击我"框之前,

jQuery如何使用bind()方法?代码示例3

点击"点击我"框后,

jQuery如何使用bind()方法?代码示例4

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: