我正在显示项目ID和标题。还有一个链接“显示此成员的项目”。单击它会显示该用户的项目。为此,我使用ajax。有一个脚本可以检测单击复选框。此选项对于第一个列出的项目正常工作,但对ajax返回的项目无效
<table id="result" width="100%"> <?php if($tot1>0){ while($row5=mysql_fetch_array($result1)) { ?> <tr class="detail9txt" height="30"> <td width="2%"><input type="checkbox" name="item" value="<?=$row5[item_id];?>"></td> <td align="center" width="12%" style="vertical-align:baseline;"><a href=""><?=$row5['item_title'];?></a> </td> </tr> <tr><td colspan="6" align="right"><a href="javascript:callfunc(<?= $row5[user_id]; ?>)" style="font-size:10px;">Show items for this Member</a></td></tr> <?php }} ?> </table> <input name="hidden_field" type="hidden" id="hidden_field"/> <input type="image" name="submit" src="images/submito.gif" value="submit">
脚本代码和ajax是
<script type="text/javascript"> function callfunc(str) { //alert(str); if (str.length==0) { document.getElementById("result").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("result").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getdetails.php?cid="+str,true); xmlhttp.send(); } </script> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> <!-- $(document).ready(function () { var array = []; $('input[name="item"]').click(function () { if ($(this).attr('checked')) { // Add the new element if checked: array.push($(this).attr('value')); alert(array); //hidden_field.value = array.join(','); //hidden_field.value = array.join(','); document.getElementById('hidden_field').value=array.join(','); } else { // Remove the element if unchecked: for (var i = 0; i < array.length; i++) { if (array[i] == $(this).attr('value')) { array.splice(i, 1); } } } }); }); //--> </script>
getdetails.php代码是
<?php require 'include/connect.php'; $cid=$_GET['cid']; $sql="select * from table where user_id=$cid"; $res=mysql_query($sql); $tot=mysql_num_rows($res); if($tot>0){ while($row=mysql_fetch_array($res)) { echo '<tr class="detail9txt" height="30"> <td width="2%"><input type="checkbox" name="item" value="'.$row[item_id].'"></td> <td align="center" width="12%" style="vertical-align:baseline;"> <a href="">'.$row['item_title'].'</a> </td> </tr>'; }} ?>
使用此脚本
<script type="text/javascript"> var array = []; $('#item').live('click', function() { if ($(this).attr('checked')) { // Add the new element if checked: array.push($(this).attr('value')); document.getElementById('hidden_field').value=array.join(','); } else { // Remove the element if unchecked: for (var i = 0; i < array.length; i++) { if (array[i] == $(this).attr('value')) { array.splice(i, 1); } } } }); </script>