如何调用动态生成内容的点击事件


how to call click event of dynamically generated content?

我在控制器中显示以下数据。

<?php
$i=0;
foreach($this->session->userdata('data') as $item)
{
    //echo "<pre>"; print_r($item); echo "</pre>";
    $query = $this->db->query("SELECT product_name FROM phppos_product WHERE  
product_id='".$item['product_id']."'");
    foreach ($query->result() as $row)
{
$product_name=$row->product_name;
}
    echo "<tr>";
    echo "<td>".$product_name."</td>";
    echo "<td>".$item['quantity']."</td>";
    echo "<td>".$item['unit']."</td>";
    echo "<td>".$item['unit_rate']."</td>";
    echo "<td><a href='javascript:void(0)' rownum='".$i."' class='remove_from_cart'><img
 src='images/close.png'/></a></td>";
    echo "</tr>";
    $i++;
 }
 ?>

关于 ajax 成功的查看文件...

    $.post( followurl, {'product_id' :
      product_id,'quantity':quantity,'unit':unit,'unit_rate':unit_rate}, function(data){
        //alert(data)   ;   
        $("#cart_details").html(data);
        $("#quantity").val('');
        $("#unit").val('');
        $("#unit_rate").val('');
        $("#add_to_cart_status").css("visibility", "hidden");           
        });
     $(".remove_from_cart").click(function() {
     alert("dsasdas");
     var array_index = $(this).attr('rownum');
      alert(array_index);
     var followurl  ='<?php echo base_url()."index.php/placeorder_ajax/remove_from_cart";?>';
     $.ajax({
            method: "GET",
            url: followurl,
            data : {'array_index':array_index}
            success: function(data, status){
                                                $("#cart_details").html(data);
                                            }
            });
    });

现在我想在单击remove_from_cart类时调用另一个函数。但是警报不会在点击remove_from_cart类时出现。所以有人知道吗??

请注意,我在控制器中显示数据

它不起作用,因为您在页面上存在项目之前附加事件。

添加内容时附加事件或使用事件委派。

$(document).on("click", ".remove_from_cart", function() {
    alert("dsasdas"); 
});
$("#cart_details").on('click', '.remove_from_cart', function () {
        alert("dsasdas");
        var array_index = $(this).attr('rownum');
        alert(array_index);
        var followurl = '<?php echo base_url() . "index.php/placeorder_ajax/remove_from_cart"; ?>';
        $.ajax({
        method: "GET",
                url: followurl,
                data : {'array_index':array_index}
        success: function(data, status){
        $("#cart_details").html(data);
        }
    });
    });

您专注于波纹管部分

$("#cart_details").on('click', '.remove_from_cart', function () {
    alert("dsasdas");
});