I know there are a lot of answered questions here, but I think this is a more specific problem.
I populate a div with dynamically generated products. Each product has an input field with a plus and min button to adjust the amount inside the input.
Whatever I try I can't get it to work. I know I have to use on
to click dynamic elements.
My HTML
<div class="carousel-wrapper">
<div class="custom-products" data-getnew="popular-products"></div>
</div>
<div class="carousel-wrapper">
<div class="custom-products" data-getnew="newest-products"></div>
</div>
My Jquery
function customProducts(url, container){
$.get(url + '?format=json', function(e){
var productsHtml = [];
$.each(e.products, function(index, product) {
var productHtml = '<div class="col col-25 m-50 t-25 item-grid"><div class="item quick-view-item clearfix" data-handle="'+product.url+'" data-vid="'+product.vid+'">
.......
.......
productHtml = productHtml + '<div class="to-cart"><form action="/cart/add/'+product.vid+'" id="product_configure_form_'+product.id+'" method="post"><div class="custom-quantity-input"><input type="text" name="quantity" value="1"><div class="item-quantity-btns"><div class="up quantity-btn quantity-input-up"><i class="fa fa-plus"></i></div><div class="down quantity-btn quantity-input-down"><i class="fa fa-minus"></i></div></div></div><button type="submit" class="item-add-btn-cart btn btn-custom-1 with-qty redirect" title=""></button></form></div> </div> </div> </div> </div>';
productsHtml.push(productHtml);
});
productsHtml = productsHtml.join('');
$(container).html(productsHtml);
})
}
And then run it like this:
$(function(){
$('.carousel-wrapper .custom-products').each(function(){
var url = $(this).data('getnew')
var container = $(this)
customProducts(url, container)
});
To click the plus/min buttons
$('.carousel-wrapper .custom-products').each(function(){
$('.item-grid').on('click', '.up', function (){
console.log($(this))
alert('test')
});
$('.item-grid').on('click', '.down', function (){
console.log($(this))
alert('test')
});
});
.....
Why does this not work? Console and alert don't show anything. To my understanding you have a static container with the dynamic items and then you select the button with .on
. What's wrong with that?
Any help greatly appreciated.
当动态创建元素时,必须在文档上触发事件。
$(document).on('.item-grid .down', 'click', function (){
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.