如何将选中的option值赋值给a标签的data-size属性?
Let's fix this step by step. First, we'll make a small improvement to your PHP-generated select to add a class (for easier targeting), then update the JavaScript to handle the selected size correctly.
Step 1: Add a Class to the Select Element
Modify your PHP code to give the select a unique class. This makes it simpler to target in JavaScript:
<?php $values = get_field('size'); if($values) { echo '<select class="product-size-select">'; foreach($values as $value) { echo '<option>' . $value . '</option>'; } echo '</select>'; } ?>
Step 2: Update the JavaScript (Recommended Approach)
Instead of updating the data-size attribute every time the select changes, we can directly grab the selected value when the "Add Item" button is clicked. This is more reliable and avoids keeping attributes in sync:
$('.add-to-cart').click(function (event) { event.preventDefault(); const $button = $(this); // Get existing data from the button const name = $button.data('name'); const price = Number($button.data('price')); const article = $button.data('article'); // Get the selected size from the adjacent select const selectedSize = $button.siblings('.product-size-select').val(); // Validate size selection if (!selectedSize) { alert('Please select a size before adding to cart!'); return; } // Add to cart with the selected size shoppingCart.addItemToCart(name, price, article, selectedSize, 1); displayCart(); });
Alternative Approach: Update data-size on Select Change
If you specifically need to update the data-size attribute when the user selects an option, add this event listener alongside the click handler:
// Update data-size whenever the select option changes $('.product-size-select').on('change', function() { const selectedSize = $(this).val(); // Update the adjacent add-to-cart button's data-size $(this).siblings('.add-to-cart').data('size', selectedSize); }); // Modified click handler using the updated data-size $('.add-to-cart').click(function (event) { event.preventDefault(); const $button = $(this); const name = $button.data('name'); const price = Number($button.data('price')); const article = $button.data('article'); const size = $button.data('size'); if (!size) { alert('Please select a size before adding to cart!'); return; } shoppingCart.addItemToCart(name, price, article, size, 1); displayCart(); });
Note on HTML Structure
If your select and button aren't direct siblings (e.g., they're inside different divs), use closest() to find a shared parent container, then target the select:
// For non-sibling elements const selectedSize = $button.closest('.product-container').find('.product-size-select').val();
内容的提问来源于stack exchange,提问作者Slava Core

