javascript - Unable to bind function on dynamically created element -
this question has answer here:
i'm creating simple shopping cart javascript, , shopping cart without button remove item be?
the cart created on-the-fly javascript, elements won't exist on page load. however, shouldn't problem this?
$(".removefromcart").on("click",function(e){ alert("go away please.."); var tuoteid = $(this).attr("data-id"); deletefromcart(tuoteid); });
the element (created on fly) looks this:
<a href="#" class="removefromcart" data-id="2">×</a>
but won't trigger. if replace .replacefromcart
with, example, p
, trigger every time click on paragraph.
this isn't first time i'm having problems .on()
, takes half of hair solve, maybe more experience point me i'm doing wrong.
you need event delegation, using other version of jquery on() function. have give static parent present time binding code executed or can delegate body
or document
.
$(document).on("click",".removefromcart", function(e){ alert("go away please.."); var tuoteid = $(this).attr("data-id"); deletefromcart(tuoteid); });
delegated events have advantage can process events descendant elements added document @ later time. picking element guaranteed present @ time delegated event handler attached, can use delegated events avoid need attach , remove event handlers, jquery doc.
Comments
Post a Comment