遍历列表项并跳过指定编号生成标签(固定HTML结构)
Solution for Custom Numbered List Items (Skipping Specific Numbers)
Got it, let's solve this problem exactly as you requested—no modifying the list structure, just updating <span> elements to show custom numbers that skip your specified values.
Step 1: Assumed Initial HTML Structure
First, let's confirm the HTML setup (I'm assuming your list items already have an empty <span> for the custom number, since you mentioned using <span> to set the value):
<ul class="target-list"> <li><span class="custom-number"></span> First list item</li> <li><span class="custom-number"></span> Second list item</li> <li><span class="custom-number"></span> Third list item</li> <li><span class="custom-number"></span> Fourth list item</li> <li><span class="custom-number"></span> Fifth list item</li> <li><span class="custom-number"></span> Sixth list item</li> <li><span class="custom-number"></span> Seventh list item</li> <li><span class="custom-number"></span> Eighth list item</li> <li><span class="custom-number"></span> Ninth list item</li> <li><span class="custom-number"></span> Tenth list item</li> </ul>
Step 2: jQuery Implementation
Here's the code that will generate the correct numbers (skipping 3,6,8,9,13) without touching the list structure:
$(document).ready(function() { // Define the numbers we need to skip (using Set for fast lookups) const skippedNumbers = new Set([3, 6, 8, 9, 13]); let currentCounter = 1; // Loop through each number span in the list $('.target-list .custom-number').each(function() { // Skip any numbers in our excluded set while (skippedNumbers.has(currentCounter)) { currentCounter++; } // Set the span's text to the valid counter value $(this).text(currentCounter); // Move to the next number for the next item currentCounter++; }); });
How This Works
- No DOM Structure Changes: We're only updating the text content of existing
<span>elements—no.append(),.remove(), or other methods that alter the list's structure. - Efficient Skipping: Using a
Setfor skipped numbers makes checking if a number should be skipped extremely fast (O(1) time complexity). - Dynamic Counting: The loop automatically adjusts the counter to skip your specified numbers, so even if you add more list items later, it will keep generating valid numbers without manual updates.
For your example of 10 list items, this code will output exactly the sequence you wanted: 1、2、4、5、7、10、11、12、14、15.
内容的提问来源于stack exchange,提问作者lvlzero
相关产品推荐
相关产品推荐

