使用.loaddata后如何触发函数

How to trigger function after using .loaddata

我想知道为什么我无法在加载了 .loaddata 函数的按钮上执行 jquery 函数。

<div id="products"></div>

<script>
$(document).ready(function(event) {
    loadData(1,'default');
});

function loadData(page,type){
    var base = '<?php echo $sr_class->baseURL();?>';
    $.ajax
    ({
        type: "GET",
        url: base+"includes/module/loadProduct.php",
        data: {page:page,type:type},
        success: function(msg)
        {
            console.info(msg);
            $("#products").html(msg);
        }
    });
}
$('.addcart').click(function(e){
    e.preventDefault();
    var proid = $(this).attr('proid');
    var base = '<?php echo $sr_class->baseURL();?>';
    $.post(base+'includes/module/addtocart.php',{p_id:proid, p_qty:1},function(result){
        location.reload();
    })
});

</script>

来自 loadData 函数的 'msg' return 是:

<p><a proid="ABCD1001" class="btn btn-success addcart" role="button"> ABCD1001</a></p>

当我点击按钮时,它没有执行功能。

那是因为您使用的是 .click() 而不是 .on()。您正在使用的 click() 绑定称为 "direct" 绑定,它只会将处理程序附加到已经存在的元素。它不会绑定到将来创建的元素。为此,您必须使用 on().

创建 "delegated" 绑定

来自documentation of .on()

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

所以将 .addcart 元素与 .on() 绑定,如下所示:

$(document).on('click','.addcart',function(e){
    e.preventDefault();
    var proid = $(this).attr('proid');

    $.post('<?php echo $sr_class->baseURL();?>includes/module/addtocart.php',{p_id:proid, p_qty:1},function(result){
        location.reload();
    })
});