我创建了一个php页面,其中一个表是从数据库构建的。每个单元格都是禁用输入文本,应该通过鼠标单击激活。一旦启用和修改,按下回车键(我打开其他解决方案,我没有想到这一点)应该将新值存储在数据库中,在表中显示并再次禁用该字段。
我没有设法切换输入字段的disabler属性,也没有设置其他所有内容(在禁用/启用功能正常工作之前无法执行此操作)。
这些是代码的一部分,可以帮助您理解我的意思。
这是您可以在下面的代码中看到的CSS:
<style type="text/css">
.clickable, input[type="text"]:disabled, input[type="number"]:disabled {
cursor: hand;
}
.clickable:hover {
background: #dcd2ff;
}
input[type="text"]:disabled, input[type="number"] {
background-color: rgba(255,0,0,0);
border: 0px;
width: 100%;
height: 100%;
}
</style>
这是我第一次看到JS,这就是我认为启动器应该是:
<script type="text/javascript">
function edit(cellID) {
var cell = document.getElementById(cellID);
cell.disabled = !cell.disabled;
}
</script>
这就是我构建表格的方式:
<table>
<?php
// DB connection + select query
for ($i = 0; $i < $num; $i++)
{
// Getting, for example, $a and $b values
$line_color = ($i % 2 == 0) ? "pair" : "dispair";
echo "<tr class=\"$line_color\">";
echo " <td class=\"clickable\">";
echo " <input id=\"$i-1\" onclick=\"edit('$i-1')\" type=\"text\" value=\"$a\" disabled />";
echo " </td>";
echo " <td class=\"clickable\">";
echo " <input id=\"$i-2\" onclick=\"edit('$i-2')\" type=\"number\" value=\"$b\" disabled />";
echo " </td>";
echo "</tr>";
}
?>
</table>
此处您有“另一种观点”: http://jsfiddle.net/vL2rw/
答案 0 :(得分:0)
这是表格单元格输入元素的工作解决方案。可能不是最好的代码,曾经和jQuery一起工作所以原谅我=) http://jsfiddle.net/vL2rw/6/
var clickables = document.getElementsByClassName("clickable");
for(var i = 0; i < clickables.length; i++){
clickables[i].addEventListener("click", edit, true);
}
function edit(){
var input = this.getElementsByTagName("input")[0];
input.removeAttribute("disabled");
input.focus();
input.addEventListener("blur", save, false);
}
function save(){
this.setAttribute("disabled", "disabled");
// Do your saving here (by ajax?)
alert("Save!");
}
索姆指出要考虑:
- 使用jQuery与IE8等旧版浏览器兼容(或使用事件处理程序而不是事件监听程序)
- 也许在通过ajax将值发送到db之前检查输入中的值是否已更改
- 我使用“模糊”事件,如果你想要那么就改成输入