2016年9月8日 星期四

jQuery 動態加載內容(Ajax or append) 事件綁定無效解決辦法:.on()

參考:
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()
- 但只有寫死的有效動態加載的卻失效
- 舉例:
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <link rel="stylesheet" href="cssName.css">
  6. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  7. <title>aaa</title>
  8. <script>
  9. $(function(){
  10. $('#btn').click(function(){
  11. $('#the_div').append('<button>new button</button>');
  12. })
  13.  
  14. $("#the_div button").click(function(){
  15. alert('clicked');
  16. })
  17. });
  18.  
  19. </script>
  20. </head>
  21. <body>
  22. <div id="the_div">
  23. <button>new button</button>
  24. </div>
  25. <button id="btn">test</button>
  26. </body>

3.Why
- 第一次$(function(){}) 載入html時,只有寫死的new botton有被『註冊
- 後面動態加載的並沒有被載入

4.Solution
- 使用.on方式
- $( document ).on( events, selector, data, handler );
- 舉例,將方法置換成下列程式

  1. $(document).on('click','#the_div button',function(){
  2. alert('clicked');
  3. })

沒有留言:

張貼留言