我有一个表单,我希望能够通过双击它来编辑该表单的任何部分。所以从这个开始:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>John Smith</td>
<td>johnsmith@gmail.com</td>
<td>+12345678</td>
</tr>
</table>
如何通过双击一个元素,将其转换为输入元素?
例如:如果我双击 John Smith
,HTML 将变为:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<form action="index.php" method="post">
<td><input type="text" value="John Smith" name="name" /></td>
<td>johnsmith@gmail.com</td>
<td>+12345678</td>
</form>
</tr>
</table>
有人知道怎么做吗?
最佳答案
试试这个,第二行的字段可以用 dblclick 编辑
document.querySelectorAll("table tr:nth-child(2) td").forEach(function(node){
node.ondblclick=function(){
var val=this.innerHTML;
var input=document.createElement("input");
input.value=val;
input.onblur=function(){
var val=this.value;
this.parentNode.innerHTML=val;
}
this.innerHTML="";
this.appendChild(input);
input.focus();
}
});
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>John Smith</td>
<td>johnsmith@gmail.com</td>
<td>+12345678</td>
</tr>
</table>
关于javascript - 通过双击元素编辑表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48977986/