首页 > 解决方案 > 动态创建的按钮和它自己的值

问题描述

如何获得data-index点击按钮:

var removePair = $("button[name=removePair]"),
    tbody = $('tbody[name=tb-table]'),  

function DrawHtml(list) {
    var html = '';
    for (var i = 0; i < list.length; i++) {
        var o = list[i];
        html += '<tr name="row-' + i + '">';
        html += '   <td>';
        html += '       <button name="removePair" data-index="' + i + '" class="btn btn-primary mx-1" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
        html += '   </td>';
        html += '</tr>';
    }
    return html;
}

$(tbody).on("click", removePair, function () {
    console.log($(this));
    console.log($(this).val());
    console.log($(removePair));
});

我知道在动态添加的按钮上添加事件的唯一方法是将其附加到parrent(tbody),并通过动态创建的按钮触发removePair,但我不知道如何点击以获得removePair进一步的逻辑。

this返回tbody而不是removePair

谢谢!!

标签: javascriptjquery

解决方案


您应该将选择器传递给.on()方法而不是元素。由于元素是动态创建的,因此$("button[name=removePair]")不存在。

采用

removePair = "button[name=removePair]"

var removePair = "button[name=removePair]",
  tbody = $('tbody[name=tb-table]');


function DrawHtml(list) {
  var html = '';
  for (var i = 0; i < list; i++) {
    html += '<tr name="row-' + i + '">';
    html += '   <td>';
    html += '       <button name="removePair" data-index="' + i + '"  type="button">' + i + '</button>';
    html += '   </td>';
    html += '</tr>';
  }
  return html;
}

//Create HTML
tbody.html(DrawHtml(5));

$(tbody).on("click", removePair, function() {
  console.log($(this).text());
  console.log($(removePair).length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody name="tb-table"></tbody>
</table>


推荐阅读