簡體   English   中英

jQuery單擊帶有按鈕的動態創建的元素並不起作用

[英]Jquery clicking dynamic created elements with buttons and on doesn't work

我知道這里有很多回答的問題,但是我認為這是一個更具體的問題。

我用動態生成的產品填充div。 每個產品都有一個帶有加號和減號按鈕的輸入字段,用於調整輸入中的數量。

無論我嘗試什么,我都無法正常工作。 我知道我必須使用on點擊動態元素。

我的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>

我的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);
    })
}

然后像這樣運行它:

$(function(){

$('.carousel-wrapper .custom-products').each(function(){
  var url = $(this).data('getnew')
  var container = $(this)
    customProducts(url, container)
});

單擊加/分按鈕

$('.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')
   });
 });
 .....

為什么這不起作用? 控制台和警報不顯示任何內容。 據我了解,您有一個包含動態項目的靜態容器,然后使用.on選擇按鈕。 怎么了

任何幫助,不勝感激。

當動態創建元素時,必須在文檔上觸發事件。

$(document).on('.item-grid .down', 'click', function (){

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM