jQuery交换指定ID的两个DIV位置时出现重复问题求助
Troubleshooting Duplicate
#multi_stops Divs Let's break down why you're seeing duplicate elements and fix the issue step by step:
Key Issues Identified
- Invalid HTML Structure:
<li>elements can only be direct children of<ul>or<ol>tags. Your current code nests<li>inside<span>and<div>, which forces browsers to auto-correct the markup—this often leads to unexpected rendering that looks like duplicate elements. - Redundant Positioning Logic: You're calling
insertBefore/insertAfterinside your loop over stops. This is unnecessary (you only need to swap positions once based onvalue) and can contribute to odd behavior even if it doesn't directly duplicate the div.
Step 1: Fix the HTML Structure
First, correct the invalid markup by wrapping <li> elements in <ul> containers:
<div id="before_stops"> <ul> <li> <span><img src="<?php echo base_url('assets/images/multi_stops.png') ?>" width="18px" height="18px"/></span> <div class="verticalLine"></div> <span class="text multi_non_append_stops"></span> <br><br> </li> </ul> </div> <div id="multi_stops"> <ul class="text multi"> <li> <span><img src="<?php echo base_url('assets/images/EndPoint.png')?>" width="18px" height="18px"></span> <div class="verticalLine"></div> <br/><br> </li> </ul> </div>
Step 2: Adjust Your JavaScript Code
Move the position-swap logic outside the loop (we only need to do this once) and keep the content appending inside the loop:
// Handle div positioning ONCE, before processing stops if (value === "A" || value === "B") { $('#multi_stops').insertBefore($('#before_stops')); } else { $('#multi_stops').insertAfter($('#before_stops')); } // Loop through stops to append content for (var i = 0; i < data.stops.length; i++) { $('.multi').append(`<li> <span><img src="${base_url}assets/images/multi_stops.png" width="18px" height="18px"></span> <div class="verticalLine"></div> ${data.stops[i].stopDestination} <br/><br/> </li>`); }
Optional: Prevent Duplicate Content on Re-Runs
If this code might execute multiple times (e.g., on a button click), clear existing content in .multi before appending new stops to avoid duplicate list items:
// Clear existing content first $('.multi').empty(); // Then loop through stops to append new content for (var i = 0; i < data.stops.length; i++) { $('.multi').append(`<li> <span><img src="${base_url}assets/images/multi_stops.png" width="18px" height="18px"></span> <div class="verticalLine"></div> ${data.stops[i].stopDestination} <br/><br/> </li>`); }
Why This Works
- Fixing the HTML eliminates browser auto-correction that was creating unexpected elements.
- Moving the positioning logic outside the loop ensures you only rearrange the divs once, avoiding redundant operations.
- Clearing existing content (if needed) prevents duplicate list items from accumulating on repeated runs.
内容的提问来源于stack exchange,提问作者Janessa Bautista
相关产品推荐
相关产品推荐

