追加商品后“加入购物车”功能失效问题咨询
Hey there, I’ve run into this exact issue with jQuery plugins before—here’s what’s going on and how to fix it:
The Root Cause
When you initialize the myCart plugin with $('.add-cart').myCart(...), it only binds functionality to elements that exist on the page when the code first runs. Any .add-cart elements you append later (your dynamic products) don’t get that plugin initialization, so clicking them does nothing.
Solution 1: Re-Initialize the Plugin for New Elements
After you append your new product HTML to the page, target the newly added .add-cart element and initialize the plugin on it specifically. Here’s how that might look in your code:
// Example: Your code that appends the new product var newProductHtml = '<li> <a data-id="'.$newRow[0].'" data-name="'.$newRow[3].'" data-summary="'.$newRow[3].'" data-price="'.$newRow[6].'" data-quantity="1" data-image="'.$newRow[12].'" class="add-cart"> <span class="icon flaticon-shopping66 "></span> </a> </li>'; $('.your-product-container').append(newProductHtml); // Now initialize the plugin on the newly added element $('.your-product-container').find('.add-cart:last').myCart({ classCartIcon: 'my-cart-icon', classCartBadge: 'my-cart-badge', // Add all your existing plugin configuration options here });
Solution 2: Verify Dynamic Data Attributes
Double-check that all the data-* attributes (like data-id, data-price) are being correctly populated for your dynamically added products. If any of these are missing or have invalid values, the plugin might fail silently. You can inspect the element in your browser’s dev tools (F12) to confirm this.
Quick Troubleshooting Tip
Open your browser’s console (F12) and look for error messages—this can quickly tell you whether the issue is with initialization or invalid data.
内容的提问来源于stack exchange,提问作者Mad Coder

