Friday, February 13, 2015

Event - bind(), unbind(), live()

1. bind函数可以有三个参数,当第二个参数不是一个函数,而是一个数据对象时,它将默认做为bind第三个参数(函数)的参数。

<a hreft="javascript:void(0)">test</a>

var msg = "1";

$("a").bind("click", {message: msg}, function(event){
              msg = "2";
              alert(event.data.message); //get access to the value of the message parameter
}); 


//final output will be 1 since "var msg='1' " is evaluated as soon as the event handler is bound.

2. unbind()
I. $("a").unbind();
II. $("a").unbind("click doubleclick"); //unbind specific type of events
III. $("#**").unbind("click", fnName) 删除特定函数的绑定

3. live()
<div id="divTestArea1">
      <a href="javascript:void(0);" onclick="AddBox();">Add Box</a>
      <div class="test">This is a box</div>
</div>

<script type="text/javascript">
$(function()
{     //live方法类似于.bind(),除此之外,它允许你将事件绑定到DOM元素上,可以将事件绑定到DOM中还不存在的元素上. 解除live方法,使用die()方法
       $(".test").live("mouseover", function(){
                    $(this).css("background-color","blue");
           }).live("mouseout", function(){
                    $(this).css("background-color", "white");
           });
});
//if using the bind() method above, the following element will not has the above effect.
// if using the live() method, the following will do the same work with the above one.
function AddBox()
{
          var div = $("<div></div>").addClass("test").text("AnotherBox");
          $("#divTestArea1").append(div);
}
</script>


for details about live() and die():
http://www.cnblogs.com/dumuqiao/archive/2011/09/09/2172513.html

No comments:

Post a Comment