<!doctype html> <html lang="zh"> <head> <meta charset="utf-8"> <title>$(selector).on()绑定动态追加元素</title> </head> <body> <button id="add">新增</button> <ul> <li>#1</li> <li>#2</li> <li>#3</li> </ul> <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function () { var index = 3; // 用on()绑定li的点击事件,这样后续动态追加的li会自动绑定,无需全部重新绑定或单独绑定追加的li $('ul').on('click', 'li', function () { console.log($(this).html()); }); // 点击新增按钮追加li,由于前面是用on()绑定li的点击事件,追加的li会自动绑定无需再做别的操作 $('#add').click(function () { index++; $('ul').append('<li>#' + index + '</li>'); }); }); </script> </body> </html>
Copyright © 2024 码农人生. All Rights Reserved