http://www.polarxiong.com/archives/jQuery-Ajax%E5%8A%A8%E6%80%81%E5%8A%A0%E8%BD%BD%E5%86%85%E5%AE%B9on-%E7%BB%91%E5%AE%9A%E4%BA%8B%E4%BB%B6%E6%97%A0%E6%95%88%E7%9A%84%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95.html
1.Problem:
- 新增的『元素』讀取不到『事件』
2.Example:
- new botton 綁定『click』事件 → 出現 alert()
- 但只有寫死的有效,動態加載的卻失效
- 舉例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="cssName.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<title>aaa</title>
<script>
$(function(){
$('#btn').click(function(){
$('#the_div').append('<button>new button</button>');
})
$("#the_div button").click(function(){
alert('clicked');
})
});
</script>
</head>
<body>
<div id="the_div">
<button>new button</button>
</div>
<button id="btn">test</button>
</body>
3.Why
- 第一次$(function(){}) 載入html時,只有寫死的new botton有被『註冊』
- 後面動態加載的並沒有被載入
4.Solution
- 使用.on方式
- $( document ).on( events, selector, data, handler );
- 舉例,將方法置換成下列程式
$(document).on('click','#the_div button',function(){
alert('clicked');
})
沒有留言:
張貼留言