jquery bind()方法与live()方法的区别

时间:2023-01-05 18:54:20

jquery bind() 方法和 live() 方法都可以绑定元素事件。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="http://libs.baidu.com/jquery/1.8.2/jquery.js"></script>
</head>
<body>
<input type="button" id="btntest" value="点击就不可用了">
<script>
$(function () {
    $("#btntest").bind("click", function () {
        $(this).attr("disabled", "true");
    });
});
</script>
</body>
</html>

将bind换成live效果是一样的,都是在点击按钮后,按钮不可用。

那么它们的区别在哪呢?

区别就是live()方法可以绑定动态元素,而bind()方法不可以。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="http://libs.baidu.com/jquery/1.8.2/jquery.js"></script>
</head>
<body>
<script>
$(function () {
    $("#btntest").live("click", function () {
        $(this).attr("disabled", "true");
    });
    $("body").append("<input id='btntest' type='button' value='点击就不可用了' />");
});
</script>
</body>
</html>

这里如果将live换成bind就没有效果了。

注意:从 jQuery 1.7 开始,不再建议使用 .live() 方法。1.9不支持.live()