javascript - 如何使用 jquery 从动态添加的表中删除没有 id 的特定 <td> 单元格?

标签 javascript jquery html html-table

该表格包含一个下拉框和一个普通的<td>有一个值。当onChange下拉菜单中,具体<td>必须更改为另一个下拉菜单。我使用 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);
    });
  });
});

最佳答案

而不是使用nth-child ,考虑使用eq() - 它更干净,并且不存在 nth-child 的一些特异性问题.

  • 获取所有<td>在“changed”行中的元素,可以获得父<td>通过这样做.closest("td")并使用 .siblings("td") 选择其所有 sibling

  • 要包含原始的(而不仅仅是 sibling ),您可以使用 .addBack()

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

把所有的放在一起,看起来像这样:

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

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

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

关于javascript - 如何使用 jquery 从动态添加的表中删除没有 id 的特定 <td> 单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43142156/

相关文章:

javascript - 对象不支持此属性或方法 IE8 hasclass 方法

javascript - 如何以 Angular 转换数据以校正张量格式?

html - 使用表格而不是 CSS 来控制布局是否有任何合法用途?

html - 我的网页结束了,但滚动还在继续

php - ACF 页面 while 循环中断页脚 while 循环

javascript - 检测移动设备 - YouTube JS API

javascript - socket.io 对于广播应用程序无法正常工作

jquery - 使用 jquery 激活水平子菜单父链接

javascript - JQuery - 粘贴事件,剥离富文本

jquery - Bootstrap 3 导航栏菜单项 - 淡入和淡出