jQuery中的“ on”和“ live”或“ bind”有什么区别?
jQueryon()
方法
on(events[,选择器][,data],handler)方法将处理程序绑定到所有当前-和将来-匹配元素的事件(如click)。它还可以绑定自定义事件。
这是此方法使用的所有参数的描述-
事件-事件类型用空格分隔。
选择器 -选择器字符串
数据 -数据将被传递到event.data事件处理程序
handler- 绑定到每个匹配元素集上的事件的函数
示例
您可以尝试运行以下代码以了解如何使用on()
方法-
<html> <head> <title>jQuery on() method</title> <script src = "https://cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function() { $('div').on('click', function( event ){ alert('Hi there!'); }); }); </script> <style> .div { margin:10px; padding:12px; border:2px solid #666; width:60px; } </style> </head> <body> <p>Click on any square below to see the result:</p> <div class = "div" style = "background-color:blue;"></div> <div class = "div" style = "background-color:green;"></div> <div class = "div" style = "background-color:red;"></div> </body> </html>
<html> <head> <title>jQuery live() method</title> <script src = "https://cdn.staticfile.org/jquery/1.6.1/jquery.min.js"></script> <script> $(document).ready(function() { $('div').live('click', function( event ){ alert('Hi there!'); }); }); </script> <style> .div{ margin:10px; padding:12px; border:2px solid #666; width:60px; } </style> </head> <body> <p>Click on any square below to see the result:</p> <div class="div" style="background-color:blue;"></div> <div class="div" style="background-color:green;"></div> <div class="div" style="background-color:red;"></div> </body> </html>
注意live()
-jQuery1.7中已弃用的jQuery方法。终于在jQuery1.9中将其删除。要运行以下程序,请使用1.7之前的jQuery版本。
jQuerybind()
方法
bind(type,[data],fn)方法将处理程序绑定到每个匹配元素的一个或多个事件(如click)。它还可以绑定自定义事件。
这是此方法使用的所有参数的描述-
type- 一种或多种事件类型,以空格分隔。
数据 -这是可选参数,表示作为event.data传递到事件处理程序的其他数据。
fn- 绑定到每个匹配元素集上的事件的函数。
示例
您可以尝试运行以下代码以了解如何使用bind()
方法-
<html> <head> <title>jQuery bind() method</title> <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $('div').bind('click', function( event ){ alert('Hi there!'); }); }); </script> <style> .div { margin:10px; padding:12px; border:2px solid #666; width:60px; } </style> </head> <body> <p>Click on any square below to see the result:</p> <div class = "div" style = "background-color:blue;"></div> <div class = "div" style = "background-color:green;"></div> <div class = "div" style = "background-color:red;"></div> </body> </html>