如何处理引导程序按钮的onclick事件?

时间:2019-06-27 03:48:30

标签: jquery twitter-bootstrap

我有一个ajax调用,用json响应的结果填充表(每次用户在文本框上键入内容时,我都会进行调用-keyup事件处理程序),我可以正确填充表,但是如果我愿意单击“详细信息”按钮,该处理程序不执行任何操作。我尝试了不同的方法,但没有一个起作用。

我尝试使用类选择器和id选择器,但是没有一个按预期方式工作。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 
</script>

<script>
$(document).ready(function () {

function getCustomerInfo(keyword) {
  $.ajax({
    url: "/estimates/search/customer/" + keyword,
    data: "{}",
    dataType: "json",
    success: function (data) {
      console.log(data);
      var row = "";
      row += "<table id='customersResult' class='table table-hover' style='border: 1px solid black'>";
      row += "<thead><th scope='col'>Id</th><th scope='col'>Name</th><th scope='col'>&nbsp;</th></thead>";
      row += "<tbody>";
      $.each(data,
        function (index, item) {
          row += "<tr id='customerRow' value=" + item.id + "><td scope='row'>" + item.id + "</td>";
          row += "<td>" + item.name + "</td>";
          row += "<td><button id='detailsCustomer' class='btn btn-success'>Details</button></td>";
          row += "<td><a href='http://www.google.com' id='fire' class='btn btn-success'>Details</a></td>";
          row += "</tr>";
        });
      row += "</tbody>";
      row += "</table>";
      $("#customers").html(row);
    },
    error: function (result) {
      alert("Error");
    }
  });
}

$("#fire").on('click',
  function(e) {
    alert('Pressing anchor');
  });

$("#detailsCustomer").on('click', function (e) {
  alert('Button was clicked...');
});

$("#txtCustomer").keyup(function () {
  getCustomerInfo($('#txtCustomer').val());
  console.log('key pressed: ' + $('#txtCustomer').val());
});

$("#customersResult").on('click', '.btn', function () {
  var currentRow = $(this).closest("tr");
  var currentCol = currentRow.find("td:eq(0)").text();

  alert('Button clicked...' + currentCol);
});

});
</script>

<input type="text" id="txtCustomer" name="CustomerName" class="form-control" style="width: 500px" />
<br />
<br />
<div id="customers">

</div>

我需要检索每行第一列中的ID。我在控制台中没有任何错误,只是它什么都不做。

1 个答案:

答案 0 :(得分:0)

您需要使用委托事件处理程序。因为您的元素是虚拟元素。

$("body").on('click', '#detailsCustomer', function (e) {
   alert('Button was clicked...');
});
相关问题