如何获取td的值并将其传递给每个td元素的输入?

时间:2015-05-12 09:33:05

标签: javascript jquery html

我仍然是jQuery世界的新手:)我正在制作看起来像这样的东西,我的问题是获取每个<td>中的文本并将其传递给输入。

我有这段代码:

<div class="grid-l1">
  <table>
    <tr>
      <td>
        Testing
        <input type="text">
      </td>
    </tr>
    <tr>
      <td>
        Testing 2
        <input type="text">
      </td>
    </tr>
  </table>
    <span class="edit">Edit</span>
    <span class="update">Update</span>
</div>

这是我的jQuery代码:

<script>
    $(document).ready(function(){
        $('body').on('click', '.edit', function() {
            $(this).hide();
            $('table tr td input').show();
            $('.update').show();
        });

        $('.update').click(function(){
            $(this).hide();
            $('table tr td input').hide();
            $('.edit').show();
        });
    });
</script>

当我点击编辑时,如何获取td文本并将其传递到td元素的每个输入?

我将感谢你们所做的每一个回应。提前谢谢。

2 个答案:

答案 0 :(得分:0)

您需要的是使用td获取text()的文字,然后将其添加到输入val

此处为代码:

$(document).ready(function(){
    $("input").hide();
        $('body').on('click', '.edit', function() {
            $(this).hide();
            $("table td").each(function() {
                $(this).find("input").val($.trim($(this).text()))
            });
            $('table tr td input,.update').show();
        });

        $('.update').click(function(){
            $(this).hide();
            $('table tr td input').hide();
            $('.edit').show();
            $("table input").each(function() {
                $(this).parent().text($(this).val())
            });
        });
    });

演示http://jsfiddle.net/1yz8dc3t/

答案 1 :(得分:0)

您需要获取包含regex的{​​{1}}的{​​{1}}并设置其值。试试这个:

text()

Example fiddle