附加具有从PHP返回的特定ID的按钮不起作用

时间:2017-06-29 07:31:08

标签: javascript php jquery pdo append

通过Ajax和PHP添加时,我将一个按钮添加到一行:

var addHistory = function()
{
   var patient_medication = $("#patient_medicationn").val();
   var disease = $("#disease option:selected").text();
   var patient_side_effect = $("#patient_side_effect").val();
   var pid = $("#pid").val();
   var elem = '<button type="button" class="btn btn-danger btn-sm" 
                    id="delete_disease" name="delete_disease"><i class="fa fa-remove"></i>
                  </button>';
   $.ajax({
      url: '../php/history.php',
      data: {pid: pid, patient_medication: patient_medication, disease: 
             disease, patient_side_effect: patient_side_effect},
      type: 'POST',
      dataType: 'TEXT',

      success:function(resp)
      {
         console.log(resp)
         $("#after_th").after("<tr id='resp'><td>"+disease+"</td><td>"+patient_medication+"</td><td>"
      +patient_side_effect+"</td><td>"+elem+"</td></tr>")
      },
      error:function(resp)
      {
          console.log(resp)
      }
})

}

点击:

$(document).ready(function()
{
   $("#add_history").on('click', addHistory);
});

在我的php文件中:

$addHistory = "INSERT INTO history(patient_medication, patient_side_effect, disease, patient_id, clinic_id)
    VALUES(:patient_medication, :patient_side_effect, :disease, :patient_id, :clinic_id)";
$ExecAddHistory = $conn->prepare($addHistory);
$ExecAddHistory->bindValue(':patient_medication', $patient_medication);
$ExecAddHistory->bindValue(':patient_side_effect', $patient_side_effect);
$ExecAddHistory->bindValue(':disease', $disease);
$ExecAddHistory->bindValue(':patient_id', $pid);
$ExecAddHistory->bindValue(':clinic_id', $clinic_id);
$ExecAddHistory->execute();

$lastId = $ExecAddHistory->lastInsertId();
echo $lastId;

我回复了最后一个插入ID,因此我可以将其附加到新添加的<tr>,然后直接用户点击删除按钮,直接删除添加历史记录时发生错误。

现在一切正常,新行正在追加,但它的删除按钮根本不起作用。

现有行的删除按钮工作正常:

$("#delete_disease ").on('click', function()
{
    var elem = $(this).closest('tr');
    console.log(elem)
    var patient_medication_id = $(this).closest('tr').attr('id');
    var pid = $("#pid").val();
    if(confirm("Are you sure that you want to remove the selected history?"))
    {
        $.ajax({
            url: "../php/deleteDiseaseFromHistory.php",
            type: 'POST',
            data: { pmid: patient_medication_id, pid: pid},
            dataType: 'TEXT',
            success:function(resp)
            {
                if(resp="deleted")
                {
                    elem.fadeOut(800, function() {
                        //after finishing animation
                    });
                }
            },
            error:function(resp)
            {
                alert("Please try again");
            }
        });
    }
});

1 个答案:

答案 0 :(得分:2)

你需要

$(document).on('click', '#delete_disease ', function(event)

取代

$("#delete_disease ").on('click', function()

由于内容已通过AJAX加载。