我當時的處理方法是在添加的時候手工綁定事件處理函數。不過新版的jquery已經添加了這個功能。我們已經不需要爲此煩惱了。
參考:http://api.jquery.com/live/
最普通的動態天劍事件用法是這樣:
$('li').click(function(){
alert("點我幹麼")
})
那我們看一個簡單實例,實例1:<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>jQuery 動態綁定事件</title>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<h1> jQuery 1.7版本以上 動態添加元素事件綁定 簡單實例</h1>
<ul>
<li> 默認存在,點我試試</li>
</ul>
<button onclick="appendTest();"> 追加列表項</button>
<script>
$('li').click(function(){
alert("點我幹麼")
})
function appendTest(){
$('li:last').clone().appendTo( $('ul:last'));
$('li:last ').text("動態增加,點我試試");
}
</script>
</body>
</html>
我們繼續看 實例2:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>jQuery 動態綁定事件</title>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<h1> jQuery 1.7版本以上 動態添加元素事件綁定 簡單實例</h1>
<ul>
<li onclick="clickTest();"> 默認存在,點我試試</li>
</ul>
<button onclick="appendTest();"> 追加列表項</button>
<script>
function appendTest(){
$('li:last').clone().appendTo( $('ul:last'));
$('li:last ').text("動態增加,點我試試");
}
function clickTest(){
alert("點我幹麼")
}
</script>
</body>
</html>
用法如下:
$('.li').live('click', function(){
alert("點我幹麼")
});
但是在1.7版本以後,live 方法被廢棄了,詳情參照:
取而代之的是 on 方法,個人感覺用法變複雜了,但習慣了也還好:
我們將實例1稍加修改,用 on方法實現爲動態添加元素綁定事件:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>jQuery 動態綁定事件</title>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<h1> jQuery 1.7版本以上 動態添加元素事件綁定 簡單實例</h1>
<ul>
<li> 默認存在,點我試試</li>
</ul>
<button onclick="appendTest();"> 追加列表項</button>
<script>
$('ul').on('click','li',function(){
alert("點我幹麼")
})
function appendTest(){
$('li:last').clone().appendTo( $('ul:last'));
$('li:last ').text("動態增加,點我試試");
}
</script>
</body>
</html>
至於on 方法的詳細用法可參照jQuery手冊。