Bootstrap

JQuery入门——用unbind方法移除绑定事件

1、在DOM对象的实践操作中,既然存在用于绑定事件的bind方法,也相应存在用于移出绑定事件的方法,在JQuery中,可以通过unbind方法移除所有绑定的事件或某一个事件。

2、示例代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>unbind方法移除绑定事件</title>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
  $(function(){
  function oClick(){  //自定义事件
    $("#divTip").append("<div>这是按钮二绑定的事件</div>");
  };
     $("input:eq(0)").bind("click",function(){
  $("#divTip").append("<div>这是按钮一绑定事件</div>");
});
$("input:eq(1)").bind("click",oClick);
$("input:eq(2)").bind("click",function(){
  $("input").unbind("click",oClick);
  $("#divTip").append("<div>删除按钮二事件</div>");
});
$("input:eq(3)").bind("click",function(){
  $("input").unbind();
  $("#divTip").append("<div>移出所有按钮绑定的事件</div>");
});
  })
</script>
</head>

<body>
  <div>
    <input id="button1" class="btn" value="按钮一" type="button"/>
    <input id="button2" type="button" value="按钮二" class="btn"/>
    <input id="button3" type="button" value="删除按钮二事件" class="btn"/>
    <input id="button4" type="button" value="删除所有事件" class="btn"/>
  </div>
  <div id="divTip"></div>
</body>
</html>


3、效果图预览:

点击按钮一和按钮二:



点击删除按钮二事件在点击按钮二无反应点击按钮一有反应:



点击删除所有事件后点击所有按钮无反应:


;