事件委托-选项卡案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #container { margin: 0 auto; width: 420px; } input { width: 80px; background-color: #ffffff; } input.active { background-color: grey; } #container div { width: 100%; height: 300px; text-align: center; line-height: 300px; display: none; background-color: rosybrown; } </style> </head> <body> <div id="container"> <input type="button" id="0" class="active" value="zhongyi01"> <input type="button" id="1" value="zhongyi02"> <input type="button" id="2" value="zhongyi03"> <input type="button" id="3" value="zhongyi04"> <input type="button" id="4" value="zhongyi05"> <div style="display: block;">china mobile online server 01</div> <div>china mobile online server 02</div> <div>china mobile online server 03</div> <div>china mobile online server 04</div> <div>china mobile online server 05</div> </div> </body> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> <script type="text/javascript"> // js 事件委托 $(function () { $('#container').on('click', function (ev) { console.log('event:', ev); var ev = ev || window.event; var target = ev.target || ev.srcElement; if (target.nodeName.toLowerCase() == 'input') { $('#container input').removeClass('active').eq(target.id).addClass('active'); $('#container div').css('display', 'none').eq(target.id).css('display', 'block'); console.log('index', target.id); } }); // $('#container').trigger('click'); }) </script> </html>
工欲善其事 必先利其器