多Select2下拉框自定义图标重复问题技术求助
Hey there, let's tackle this icon duplication problem you're facing. The root cause here is that your current code uses global selectors ($('b[role="presentation"]') and $('.select2-selection__arrow')) which target all existing Select2 elements every time you run the initialization. So when you set up the second dropdown, you're re-appending the icon to the first dropdown's arrow too—hence the duplication.
Here's the corrected approach, which targets only the specific Select2 instance you're initializing each time:
// Loop through each target dropdown to handle them individually $(".where__heading").each(function() { // Initialize Select2 for the current dropdown $(this).select2({ placeholder: "Try 'Belfast'", allowClear: false, }); // Get the associated Select2 container for this dropdown const $select2Container = $(this).next('.select2-container'); // Hide the default arrow and add your custom icon—only for this instance $select2Container.find('b[role="presentation"]').hide(); $select2Container.find('.select2-selection__arrow').html('<img src="images/icons/travel.svg" alt="">'); });
Why this works:
- Using
.each()ensures we handle one dropdown at a time, avoiding cross-instance interference. $(this).next('.select2-container')grabs the exact Select2 wrapper created for the current dropdown, instead of selecting all containers on the page.- We use
.html()instead of.append()to replace any existing content in the arrow element—this prevents even accidental duplication if the code runs multiple times for the same dropdown.
If you have other dropdowns with different icons, you can extend this pattern by using unique classes for each dropdown group, then adjusting the image path inside the .each() loop based on the dropdown's class.
内容的提问来源于stack exchange,提问作者Zack Reid

