基于PHP+Jquery制作的可编辑的表格的代码

2020-05-22 22:00:04易采站长站整理

table.php

<?php
header(“Content-Type:text/html;charset=utf-8”);
$mysqli=new MySQLi(“localhost”,”root”,”123456″,”xiaoqiangdb”);
if(mysqli_connect_errno){
echo “连接数据库失败”.mysqli_connect_error();
exit;
}
?>
<html>
<head>
<title>可编辑表格</title>
<link rel=”stylesheet” type=”text/css” href=”style.css”>
<script src=”jquery-1.3.2.min.js”></script>
<script src=”table.js”></script>
</head>
<body>
<?php
$sql=”select id,name,age,sex,email from users limit 0,20″;
$result=$mysqli->query($sql);
echo “<table>”;
echo “<caption>可编辑表格</caption>”;
echo “<tr>”;
echo “<th>编号</th><th>姓名</th><th>性别</th><th>年龄</th><th>邮箱</th>”;
echo “</tr>”;
while($row=$result->fetch_assoc()){
echo ‘<tr>’;
echo ‘<td class=”id”>’.$row[‘id’]'</td>’;
echo ‘<td>’.$row[‘name’]'</td>’;
echo ‘<td>’.$row[‘age’]'</td>’;
echo ‘<td>’.$row[‘sex’]'</td>’;
echo ‘<td>’.$row[’email’]'</td>’;
echo ‘</tr>’;
}
echo “</table>”;
$mysqli->close();
?>
</body>
</html>

style.css

@charset “utf-8”;
/* CSS Document */
body{ font-size:12px; background:#EEE; text-align:center;}
table{ width:600px; border:1px solid #050; border-collapse:collapse;}
th,td{ border:1px solid #050; width:120px;}
th{ background:#282; color:white;}

table.js

// JavaScript Document
$(function(){
$(“tr:even”).css(“background-color”,”#ffff99″);
$(“tr td:not(.id)”).click(function(){
if($(this).children(‘input’).length > 0)
return;
//取出表格中原有的内容
var data=$(this).text();
//将内容设置为空
$(this).html(”);
var td=$(this);
//创建一个表格
var inp=$(‘<input type=”text”>’);
inp.val(data);
inp.css(“background-color”,$(this).css(“background-color”));
inp.css(“border-width”,”0px”);
inp.css(“width”,$(this).css(“width”));
//在表格中放一个input表单
inp.appendTo($(this));
//表单放入表格后触发焦点事件
inp.trigger(‘focus’);
//全选内容
inp.trigger(‘select’);