You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多Select2下拉框自定义图标重复问题技术求助

Fix Select2 Icon Duplication Issue When Initializing Multiple Dropdowns

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:10:20