I am wondering why i cannot execute a jquery function on a button loaded with .loaddata function.
<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>
the 'msg' return from loadData function is :
<p><a proid="ABCD1001" class="btn btn-success addcart" role="button"> ABCD1001</a></p>
When i click the button, it did not execute the function.
That's because you're using
.click()
instead of.on()
. Theclick()
binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by usingon()
.From the documentation of
.on()
:So bind
.addcart
element with.on()
like this: