HTML下拉框去重异常:JSON生成选项的包含匹配误判问题
Got it, let's work through this problem step by step. The main issues here are:
- Your initial string
includes()check was doing a partial match, so shorter options like "AAAA" got incorrectly skipped when a longer option like "AAAA & CCCC" existed. - Your original DOM-based deduplication script relied on an ID selector, but now you're using class selectors for your filters.
Here are two solid solutions to fix both problems:
Option 1: Deduplicate During HTML Generation (Better Performance)
Instead of checking if the option text is contained in the existing HTML string (which causes partial match errors), use an array to track exactly which option texts you've already added. This way you do exact matches from the start:
// Initialize an array to keep track of unique option texts const existingOptions = []; let rate_filter = ''; for (let i = 0; i < result.length; i++) { const currentOptionText = result[i][5]; // Check for exact match in the array, not partial string match if (!existingOptions.includes(currentOptionText)) { existingOptions.push(currentOptionText); rate_filter += `<option value="${i}">${currentOptionText}</option>`; } }
This approach avoids any DOM manipulation after the fact and eliminates the partial match false positives entirely.
Option 2: Adapt Your Original DOM-Based Script for Class Selectors
If you prefer to keep the post-generation deduplication approach (maybe you can't modify the HTML generation code), you can update your original script to target all select elements with your class, instead of a single ID:
// Get all select elements with your target class const filterSelects = document.querySelectorAll('.your-filter-class'); // Iterate over each select to deduplicate its options filterSelects.forEach(select => { // Convert the select's options to an array and run your original logic [].slice.call(select.options).map(function(option) { if (this[option.innerText]) { select.removeChild(option); } else { this[option.innerText] = 1; } }, {}); });
Just replace .your-filter-class with the actual class name you're using for your dropdown filters. This script will loop through every matching select, and for each one, remove duplicate options based on exact innerText matches—no more partial match issues.
Quick Note on Which to Choose
- Use Option 1 if you can modify the code that generates the HTML. It's more efficient because you don't have to clean up duplicates after they're added to the DOM.
- Use Option 2 if you need to fix existing DOM elements (e.g., the HTML is generated by code you don't control).
内容的提问来源于stack exchange,提问作者Datacrawler

