【问题标题】:How to delete a specific <td> cell with no id from a dynamically added table using jquery?如何使用 jquery 从动态添加的表中删除没有 id 的特定 <td> 单元格?
【发布时间】:2017-08-25 19:30:03
【问题描述】:

该表包含一个下拉框和一个普通的&lt;td&gt;,带有一个值。当下拉列表的onChange 时,特定的&lt;td&gt; 必须更改为另一个下拉列表。我已经使用 jQuery 来实现该功能,但是当我更改第一行的下拉列表时,整个表都发生了更改。我只需要对调用onChange 函数的单行进行更改。

$('td:nth-child(11),th:nth-child(11)').hide();
$('td:nth-child(10),th:nth-child(10)').show();

用于隐藏和显示第 10 列和第 11 列。

doc.ready 函数():

$(document).ready(function() {
  $('td:nth-child(11),th:nth-child(11)').show();
  $('td:nth-child(10),th:nth-child(10)').hide();
  // ...

使用的onChange函数:

$(document).on('change','.mySelect', function(event) {
  event.preventDefault();

  $('td:nth-child(11),th:nth-child(11)').hide();
  $('td:nth-child(10),th:nth-child(10)').show();
  //$(this).closest("td").show();

  var _this = $(this);
  var id =_this.val();
  var statusValue = id;

  $.get('AssignedTo', { statusVal : statusValue }, function(response) {
    var select = _this.closest("tr").find("select[name='assigned']");
    /* var select = $('#assigned'); */
    select.find('option').remove();

    $.each(response, function(index, value) {
      $('<option>').val(value).text(value).appendTo(select);
    });
  });
});

【问题讨论】:

  • 如果您试图获取&lt;select&gt; 所在的&lt;tr&gt;,您可以在change 事件中使用$(this).closest("tr"); 使用jQuery 选择它。 closest() 将返回与给定选择器匹配的最近的祖先,因此在您的情况下,它将匹配最近的父/祖父/等 &lt;tr&gt;
  • 尝试$(this).closest('tr').find('td:nth-child(11),th:nth-child(11)') - 这是更改后选择的最接近的tr,然后找到该行中的tds
  • 你最好在 jQuery 中使用 .eq() 而不是 nth-child。试试$(this).closest('tr').find('td').eq(10);$(this).closest('td').siblings('td').addBack().eq(10); - Demo
  • 或者代替 th 和 td 的选择器,正如 santi 所说,您可以在 children$(this).closest('tr').children().eq(10) 上执行 eq - eq 是基于 0 的索引,因此 10 是第 11 个孩子
  • 你真的应该包含你的 HTML。 Stack 上的示例通常需要完整且可验证,但只有 jQuery,您的问题都不是。 See here.我们几乎都只是在这里抓着稻草,而没有看到我们甚至试图选择什么,等等。

标签: javascript jquery html html-table


【解决方案1】:

与其使用nth-child,不如考虑使用eq() - 它更简洁,并且没有nth-child 的一些特殊性问题。

  • 要获取“已更改”行中的所有&lt;td&gt; 元素,您可以通过执行.closest("td") 获取父&lt;td&gt;,并使用.siblings("td") 选择其所有同级

  • 要包括原始的(而不是个兄弟姐妹),您可以使用.addBack()

  • 最后,既然我们已经拥有了行中的所有单元格,请使用eq() 选择您想要的单元格。

放在一起,它看起来像这样:

//Select the 11th cell in the row
var $cell = $(this).closest('td').siblings('td').addBack().eq(10);

或者,您可以使用.closest("tr")children() 获取父级并选择其所有子级(而不是兄弟级):

//Select the 11th cell in the row
var $cell = $(this).closest("tr").children("td").eq(10);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-06
    • 2023-01-03
    • 1970-01-01
    • 2016-01-17
    • 2013-03-26
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    相关资源
    最近更新 更多