javascript - 如何将文本更改为文本输入元素 - jQuery

标签 javascript jquery

我的页面中有一个表格,如下所示;

<table id="tbl" cellpadding="0" cellspacing="0" style="width: 100%">
  <tr>
    <td class="field1s">field1x</td>
    <td class="field2s">field2x</td>
    <td class="field3s">field3x</td>
    <td class="field4s">field4x</td>
    <td class="xx">#</td>
  </tr>
</table>

表格包含这么多行。当我单击最后一个单元格 (xx) 时,我希望该行中的所有其他文本都更改为 <input type="text" />分别有相应的类,里面有相应的文本。当用户再次点击 xx ,该行可能会用更改的文本进行更新。

我已经捕获了数据并做了一些工作。

Here 是 fiddle

最佳答案

我建议如下:

$('#tbl').on('click','.xx',function() {
    $(this).siblings().each(
        function(){
            // if the td elements contain any input tag
            if ($(this).find('input').length){
                // sets the text content of the tag equal to the value of the input
                $(this).text($(this).find('input').val());
            }
            else {
                // removes the text, appends an input and sets the value to the text-value
                var t = $(this).text();
                $(this).html($('<input />',{'value' : t}).val(t));
            }
        });
});

JS Fiddle demo .


编辑以回应来自@mplungjan的评论(下):

.text(something) must surely be faster and simpler to read than .text("").append(something) in any case. And you are not adding text but html so even more reason to use just html().

当然,他是对的。因此:

$('#tbl').on('click','.xx',function() {
    $(this).siblings().each(
        function(){
            if ($(this).find('input').length){
                $(this).text($(this).find('input').val());
            }
            else {
                var t = $(this).text();
                $(this).html($('<input />',{'value' : t}).val(t));
            }
        });
});

JS Fiddle demo .

引用资料:

关于javascript - 如何将文本更改为文本输入元素 - jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10862476/

相关文章:

javascript - 通过 JavaScript 抓取 Reddit 数据

javascript - Google Drive API 文件 downloadUrl 返回 401

javascript - Node repl 显示错误

c# - 如何处理渲染 asp.net MVC ChildAction 时所需的 Javascript 文件

javascript - 如何在 HTML 中更改 ul 标签 css 的属性

javascript - jquery 移动选择 onclose 事件

javascript - Cookie 写入是否会根据 Cookie 值的大小进行限制?

javascript - 当 div 清空时,Ajax 加载的弹出图像并不总是清除

javascript - 如何在悬停时从多个选择中清除选定变量的超时

JavaScript Insert table into text editor without plugins(不建议使用插件)