如何将文本更改为文本输入元素-jQuery [英] How to change text into text input element - jQuery

查看:68
本文介绍了如何将文本更改为文本输入元素-jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a table in my page as below;

<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时,该行可能会使用更改后的文本进行更新.

The table contains so many rows. When I click last cell (xx), I want all other texts in the row change to <input type="text" /> having corresponding classes respectively, with their corresponding texts inside. And when user again click xx, the row may be updated with changed text.

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

I caught data and made some work already.

这里 是小提琴

Here is the 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小提琴演示.

已编辑,以回应 在任何情况下,

.text(something)必须肯定比.text("").append(something)更快,更容易阅读.而且您不是在添加文本,而是在添加html,因此甚至有更多的理由只使用html().

.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().

当然,他是对的.因此:

He's right, of course. Therefore:

$('#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小提琴演示.

参考:

  • append().
  • each().
  • find().
  • siblings().
  • text().
  • val().

这篇关于如何将文本更改为文本输入元素-jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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