JS事件处理

jQuery可以很方便地使用Event对象对触发的元素的事件进行处理,jQuery支持的事件包括键盘事件、鼠标事件、表单事件、文档加载事件和浏览器事件等】

1)事件处理函数

<1>指定事件处理函数

jQuery选择器. 事件名(function() {
  <函数体>
  ……
} );


例如,前面多次使用的 $(document).ready() 方法指定文档对象的 ready 事件处理函数。 ready 事件当文档对象就绪的时候被触发。
<2>绑定到事件处理函数

还可以使用 bind() 方法和 delegate() 方法将事件绑定到事件处理函数。

bind(type,[data],fn)

参数说明如下。

type :事件类型。
data :可选参数,作为 event.data 属性值传递给事件 Event 对象的额外数据对象。
fn :绑定到指定事件的事件处理器函数。如果 fn 函数返回 false ,则会取消事件的默认行为,并阻止冒泡。

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>    
</head>
<body>
<input id="name"></div>
<script>
      $("input").bind("click",function() {
            alert($(this).val());
});
}); 
</script>
</body>
</html>

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>    
</head>
<body>
<input id="name"></div>
<script>
 
  function handler(event) {
    alert(event.data.foo);
  }
  $("input").bind("click", { foo: "hello" }, handler);
 </script>
</body>
</html>

使用 delegate() 方法将指定元素的特定子元素绑定到指定的事件处理函数,语法如下:

.delegate(selector, eventType,handler(eventObject) )

参数说明如下。

selector :匹配子元素的选择器。
eventType :事件类型。
handler( eventObject ) :事件处理函数。
<html>
<head>
  <style>
  p { background:yellow; font-weight:bold; cursor:pointer;
      padding:5px; }
  p.over { background: #ccc; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <p>Click me!</p>
  <span></span>
<script>
    $("body").delegate("p", "click", function(){
      $(this).after("<p>Another paragraph!</p>");
    });
</script>
</body>
</html>

<3>移除事件绑定

可以使用unbind()方法移除绑定到匹配元素的事件处理器函数。unbind()方法的语法如下:

.unbind( [eventType ] [, handler(eventObject) ] )

参数说明如下。

leventType:指定要移除的事件类型字符串,例如clicksubmit

l handler(eventObject):移出的事件处理器函数。

unbind()返回调用它的jQuery对象,从而可以实现链式操作,即在一条语句中对一个HTML元素进行多个操作。

<html>
<head>
  <style>
button { margin:5px; }
button#theone { color:red; background:yellow; }
</style>
  <script src="jquery.js"></script>
</head>
<body>
 <button id="theone">什么也不做...</button>
<button id="bind">绑定</button>
<button id="unbind">移除绑定</button>
 <script>
function aClick() {
  alert("hello");
}
$("#bind").click(function () {
$("#theone").click(aClick)
  .text("可以单击!");
});
$("#unbind").click(function () {
$("#theone").unbind('click', aClick)
  .text("什么也不做...");
}); 
</script> 
</body>
</html>


id为bind的BUtton点击之后,会将id为theone的Button的click事件处理函数指定为aClick,同时将theone的显示值设置额可以单击.

id为unbind的Button点击之后会将之前绑定在theone上的click事件处理函数取消。

unbind函数可以取消通过(1)指定事件处理函数(2)bind绑定的处理函数(3)delegate绑定的子元素处理函数.

同时要注意的是delegate是通过元素之内的子元素绑定事件处理函数,而通过#id这样的方法也可以绑定。只要将父元素选择正确,如"document"、"body".

你可能感兴趣的:(JS事件处理)