<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JQ QQ test</title> <script type="text/javascript" src="jquery-1.6.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ //print a table with 1 to 100 $("p#table").click(function(){ for(i=0;i<10;i++){ $("table#t1").append(function(){ return "<tr id="+i+"></tr>"; }); for(j=1;j<11;j++){ $("tr#"+i).append(function(){ return "<td id="+(i*10+j)+">"+(i*10+j)+"</td>"; }); } } }); $("td").click(function(){ $(this).css("background-color","red"); }); }); </script> </head> <body> <p id="table">click me to generate a table!!!</p> <table id="t1" border=1></table> <table id="test"><tr><td id="test">test</td></tr></table> </body> </html>
貌似"<td id="+(i*10+j)+">"+(i*10+j)+"</td>";这个显示不正常,如果改成"<td >"+(i*10+j)+"</td>";就显示正常了,不知道问题出在哪里= =||还有td单击响应没反应,求解答,万分感谢
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#cTable').click(function(){ for(var i=0; i<10; i++){ var all,cur = '<tr id=' + i+ '>'; for(var j=0; j<10; j++){ cur +='<td id=' + (i*10+j) +'>'+ (i*10+j) +'</td>'; } cur += '</tr>'; all += cur; } $('#myTable').append(all); }) $('td').live('click', function(){ $(this).css({background:'red'}); }) }) </script> </head> <body> <div id="cTable" class="">click this create a tabble</div> <table id="myTable" border="0" cellspacing="0" cellpadding="0" width="100%"> </table> </body> </html>
你可以先理解上面仁兄的答案,在对照这代码看一遍吧。
兄弟看来你还是没理解dom的event..
1、表格不能正常显示是因为你生成的dom的id属性重复了...导致插入时没得到你想要的结果
2、click td没反应是因为..你注册事件的代码是写在了table的td没有生成之前..如果你把td的注册代码放到p的click callback里面..你要的效果就有了...不过即便这样可行...但是却是不合理的..这种情况你应该使用事件代理来减少注册的事件数以提高性能!