在Javascript中动态更改用户输入的表格单元格 [英] Dynamically change table cell with user input in Javascript

查看:137
本文介绍了在Javascript中动态更改用户输入的表格单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要做的:我有一个表格,从每个单元格的用户输入的Javascript创建。此表仅用于确认用户输入的数据是否正确。如果用户看到错误,他们点击需要编辑的单元格,并将一个文本框放在表单元格中,并显示当前的单元格数据。如果用户点击错误的单元格,用户就可以提交更改或丢弃更改。这是目前我所拥有的:

This is what I'm trying to do: I have a table, created from Javascript with user input in each cell. This table is just to confirm that the data entered by the user is correct. If the user sees an error, they click on the cell which needs editing, and it puts a textbox in the table cell with the current cell data. The user will then be able to submit changes or discard the changes if they clicked on the wrong cell. This is currently what I have:

    <table id = "confirm">
      <tr><th>Firstname</th><td id = "txtFirstname" onclick = "update(this.id)">Adan</td></tr>
      <tr><th>Lastname</th><td>Smith</td></tr>
      <tr><th>Username</th><td>ASmith</td></tr>
      <tr><th>Email</th><td>abc@123.com</td></tr>
      <tr><th>Phone</th><td>123-456-7890</td></tr>
    </table>

<script type = "text/javascript">
  function update(id){
    //Get contents off cell clicked
    var content = document.getElementById(id).firstChild.nodeValue;
    //Switch to text input field
    document.getElementById(id).innerHTML = "<input type = 'text' name = 'txtNewInput' id = 'txtNewInput' value = '" + content + "'/>";
  }
</script>

这是我当前的代码所做的:当用户点击单元格时,它将以当前的文本框中的文本,这是非常好的,但是当您尝试编辑文本时,它会再次调用该函数,将文本替换为null。请帮我弄清楚!

This is what my current code does: When user clicks on the cell, it replaces it with the current text inside a textbox, which is great, but when you try to edit the text, it calls the function over again replacing the text with "null". Please help me figure this out!

推荐答案

这是由事件冒泡。您不希望 onclick 应用于输入,但不幸的是,情况并非如此。为了解决这个问题,只要这样做:

It is caused by event bubbling. You didn't want onclick to apply to input, but unfortunately this is not the case. To solve this problem, simply do this:

<tr>
    <th>Firstname</th>
    <td contentEditable>Adan</td>
</tr>

尝试这里: http://jsfiddle.net/DerekL/McJ4s/

为什么在简单的HTML 可以做同样的事情吗? ;

Why do it with JavaScript when simple HTML can do the same thing? ;)

IE中有一个奇怪的错误,它不会允许表单元格可编辑 (为什么,Microsoft?) 您必须使用< div> 包装您的内容:

There is a strange "bug" in IE that it won't allow a table cell to be editable (why, Microsoft?) So you have to wrap your content with a <div>:

<tr>
    <th>Firstname</th>
    <td><div contentEditable>Adan</div></td>
</tr>

尝试: http://jsfiddle.net/DerekL/McJ4s/3/

这篇关于在Javascript中动态更改用户输入的表格单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆