jQuery 更改单元格类并更新数据

jQuery change cell class and update data

本文关键字:更新 数据 单元格 jQuery      更新时间:2023-09-26

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

<table id="tbl">
  <tr>
    <td class="field" id="field1s">field1x</td>
    <td class="field" id="field2s">field2x</td>
    <td class="field" id="field3s">field3x</td>
    <td class="field" id="field4s">field4x</td>
    <td class="xx">#</td>
    <td class="yy">#</td>
  </tr>
</table>

行中字段的文本将变为<td class="xx">字段的输入,并在下次单击时更新。这工作正常。但是我希望类xx更改为aa,并在用户首次单击<td class="xx">#</td>yy bb。然后,该字段可能会更改为输入,使用户能够更改文本。如果用户再次单击"<td class="aa">#</td>"(以前<td class="xx">#</td>),则行中的文本可能会更新,如果用户单击"<td class="bb">#</td>"(以前为 #),该行可能会返回到以前的状态。(就像确定和取消一样)。

这是小提琴。

我该怎么做?我更喜欢更简单,更快捷的解决方案。

使用 jQuery .data()可以轻松解决它。我认为你不需要换课。

   $('#tbl .xx').toggle(
      function() {
        $(this).siblings('.field').each(function(){
          var t = $(this).text();
          $(this).data('prev', t);
          $(this).html($('<input />',{'value' : t}));
        });
      },
      function() {
        $(this).siblings().each(function(){
          var inp = $(this).find('input');
          if (inp.length){
            $(this).text(inp.val());
          }
        });
      }    
    );

    $('#tbl .yy').click(function() {
      $(this).siblings('.field').each(function(){
            $(this).text($(this).data('prev'));
       });
    });

演示

如果你想保留你的课程,试试这个小提琴

我使用事件委派.live()来保持与类更改的一致性。

应该删除.toggle以防止某些错误 - 例如,在codeparadox的答案中,如果您单击编辑按钮,然后单击取消按钮,则下次单击编辑按钮将触发错误的函数。

只是不要忘记.live()替换为.on()如果你在你的页面中使用jQuery 1.7+。