选择不追加在动态添加的行上的元素选项

Select element options not appending on dynamically added row

本文关键字:元素 选项 添加 追加 动态 选择      更新时间:2023-09-26

为什么当我单击添加行按钮时,不会触发foo function dos 中所选值的附加值?

  $(document).on("click", '.tdAdd', function () {
      //alert($(this).closest('tr').index());
      var newRow = $("<tr>");
      var cols = "";
      cols += '<td><input type="button" value="Add Row" class="tdAdd"/></td>';
      cols += '<td><input type="button" value="Delete" class="tdAdd"/></td>';
      cols += '<td><input type="text" /></td>';
      cols += '<td><select class = "t">' + foo($(this).closest('tr').index() + 1) + '</select></td>';
      newRow.append(cols);
      newRow.insertAfter($(this).closest("tr"));
  });

请参阅此小提琴演示。

  function foo() {
      var select = $('.t')
          .append($("<option></option>")
          .attr("value", 'one')
          .text('One'));
      select = $('.t')
          .append($("<option></option>")
          .attr("value", 'two')
          .text('Two'));
  }

问题是,您正在尝试将选项添加到当前"tr"的下一行,该行始终是 DOM 中可用的下一行(最初位于当前行旁边的那行 - 橙色行)。要在代码中准备的行中添加选项,您必须首先将其添加到 DOM 中,然后插入选项标记。

对代码的最小更改:

 $(document).on("click", '.tdAdd', function () {
      //alert($(this).closest('tr').index());
      var newRow = $("<tr>");
      var cols = "";
      cols += '<td><input type="button" value="Add Row" class="tdAdd"/></td>';
      cols += '<td><input type="button" value="Delete" class="tdAdd"/></td>';
      cols += '<td><input type="text" /></td>';
      cols += '<td><select class = "t"></select></td>';
      newRow.append(cols);
      newRow.insertAfter($(this).closest("tr"));
      foo($(this).closest('tr').index() + 1);//add options once the newly created 'select' is available in DOM
  });

您正在追加 JQuery 对象。我已经提取了 HTML 并附加了它。(见这个答案):

function foo(index) {
    var select = $("<option></option>")
                 .attr("value", 'one')
                 .text('One')
                 .prop('outerHTML');
    return select;
}

我已经更新了更新的小提琴

http://jsfiddle.net/8r0rdcLf/7/

几个问题,首先是foo()不返回任何内容,因此您尝试将undefined连接到字符串中。

接下来,您在foo()中执行的操作没有意义,因为$('.t')是具有该类的页面中每个元素的集合。


以下内容将克隆第一个选择,将其值设置为 null,然后返回要添加到字符串中的 html

  function foo(index) {
      var $select = $('.t:first').clone().val('');
      return $select.html(); // return the innerHtml of the select as string
  }

演示


为了真正简化整个addRow,您可以克隆整行,重置表单控件的值并附加该克隆...所有这些都不需要任何新字符串

$(document).on("click", '.tdAdd', function () {
    var $currentRow = $(this).closest('tr');
    var $newRow = $currentRow.clone();
    $newRow.find(':input').val('');
    $currentRow.after($newRow);
})