【问题标题】:Get Edited TD values in jQuery在 jQuery 中获取编辑后的 ​​TD 值
【发布时间】:2016-02-02 15:39:52
【问题描述】:

我有一个 HTML 表,其跨度由 PHP 变量填充。该表显示得很好,显示了数据库中存在的数据。以下是表格行,它被包裹在一个 PHP while 循环中。

<table class="table table-striped table-hover table-bordered dataTable no-footer" id="sample_editable_1" role="grid" aria-describedby="sample_editable_1_info">
  <tr role="row" class="odd">
    <td contenteditable="false" class="sorting_1">
      <span class="sl"> </span>
    </td>
    <td contenteditable="false">
      <span class="itid"><?php echo $itid1; ?></span>
    </td>
    <td contenteditable="false">
      <span class="name"><?php echo $name1; ?></span>
    </td>
    <td contenteditable="false">
      <span class="price"> <?php echo $price1; ?></span>
    </td>
    <td contenteditable="false">
      <span class="qty"><?php echo $qty1; ?></span>
    </td>
    <td>
      <button class="pr_edit" value="edit" href="javascript:;"> Edit </button>
    </td>
    <td>
      <button class="pr_elete" href="javascript:;"> Delete </button>
    </td>
  </tr>
</table>

以下是我用来提取数据的 jQuery 函数。

$('#sample_editable_1').on('click', '.pr_edit', function() {
  console.log("here");
  var currentTD = $(this).parents('tr').find('td');
  $.each(currentTD, function() {
    $(this).prop('contenteditable', true);
  });

  var ino = $(this).closest('tr').find("span.itid").text();
  var iname = $(this).closest('tr').find("span.name").text();
  var iprice = $(this).closest('tr').find("span.price").text();
  var iqty = $(this).closest('tr').find("span.qty").text();
});

但是,我无法从已编辑的字段中检索值。 TR 细胞的其余部分都可以。如何从已编辑的表格单元格中检索修改后的值?

重要提示:

我能够从未经编辑的 TR 单元格中获取值。 jQuery 选择器是正确的。

【问题讨论】:

  • 您的 html 中缺少很多关闭 &gt;s。
  • 选择器#sample_editable_1没有匹配元素
  • 我看不到。
  • 那是个问题。如果 jQuery 选择器不匹配任何 DOM 元素,您的 click 事件将不会绑定到任何东西,并且您发布的 jQuery 将永远不会运行。您的选择器需要能够找到匹配的 DOM 元素。
  • 我已经更新了这个问题。选择器效果很好。作为记录,如果没有对单元格进行编辑,我可以在 jQuery 中获取单元格值。但是,无论何时进行编辑,该特定单元格值都会更新为空白。这意味着选择器工作正常并且该字段正在重置,但没有值。

标签: javascript php jquery html html-table


【解决方案1】:

当您将contenteditable 设置为true 时,您可以使用jQuery 的data() 函数存储当前值。

例如:

$(this).data('original-value', $(this).text());

然后,当需要读取表中的所有值时,您可以将td 内容的当前值与原始值进行比较。实现将是这样的:

$('#sample_editable_1 td').each(function() {
  if ($(this).data('original-value') !== $(this).text()) {
    alert('this cell has been edited');
    alert('original value was: ' + $(this).data('original-value'));
    alert('new value is: ' + $(this).text());
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多