jquery给一个列表遍历添加点击事件

    xiaoxiao2022-07-03  116

    HTML,JS:

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="jquery-1.10.1.min.js"></script> </head> <style> *{ margin: 0px; padding: 0px; } li{ line-height: 40px; font-size: 20px; border-bottom: 1px solid #dddddd; } </style> <body> <ul class="ul_box"> </ul> <script> $(function(){ var ulbox; var _data; $.ajax({ type: "get", url: "./package01.json", data: { 'data': 'data', }, dataType: "json", success: function(data){ _data = data.employees; console.log(_data); for(var i = 0; i < _data.length; i++){ ulbox += '<li><span>' + _data[i].firstName + '</span><span>' + _data[i].lastName '</span></li>' } $('.ul_box').html(ulbox); var btn = $('.ul_box li'); $('.ul_box li').each(function(){ var _this = $(this); _this.on('click',btn,function(e){ alert( _this.children().text()); }) }) } }); }) </script> </body> </html>

    json数据:

    { "employees": [ { "firstName": "Bill", "lastName": "Gates" }, { "firstName": "George", "lastName": "Bush" }, { "firstName": "Thomas", "lastName": "Carter" } ] }

    效果图:

     

    最新回复(0)