如何将对应model-image-cell与model-info-cell配对包装进新div?
Solution to Pair Model Image and Info Cells
I get it, after converting the table structure to divs, you end up with all the image cells grouped first followed by all the info cells, but you need to wrap each image with its matching info in a separate container. Here's how to adjust your code to make that happen:
Modified Code
$("#button").click(function(){ $('#ProductDataList').replaceWith(function(){ $productListContainer = $("<div>", {html: $(this).html()}); $.each(this.attributes, function(i, attribute){ $productListContainer.attr(attribute.name, attribute.value); }); return $productListContainer; }); $('#ProductDataList tbody').contents().unwrap(); $('#ProductDataList tr').contents().unwrap(); $('#ProductDataList td').replaceWith(function(){ $div = $("<div>", {html: $(this).html()}); $.each(this.attributes, function(i, attribute){ $div.attr(attribute.name, attribute.value); }); return $div; }); // New code to pair image and info cells const $imageCells = $('#ProductDataList .model-image-cell'); const $infoCells = $('#ProductDataList .model-info-cell'); $imageCells.each(function(index) { // Create a container div for each image-info pair const $pairContainer = $('<div class="model-item-container"></div>'); // Get the current image cell and its matching info cell const $currentImage = $(this); const $currentInfo = $infoCells.eq(index); // Insert the container right where the image cell was located $currentImage.before($pairContainer); // Move both the image and info cells into the new container $pairContainer.append($currentImage, $currentInfo); }); });
How It Works
- Collect Target Elements: We first grab all the converted image cells (
model-image-cell) and info cells (model-info-cell) from the parent container. - Match Pairs by Index: Since your original table structure maintains a 1:1 order between images and their corresponding info cells, we use the same index to match each image with its info.
- Create and Position Containers: For each pair, we create a new div container, place it in the original position of the image cell, then move both the image and info cells into this container. This keeps the overall order of items intact while grouping each image with its details.
Side Note
You might want to fix the duplicate IDs in your original HTML (like ModelImageCell1 and ModelLinkCell1 repeated multiple times) — duplicate IDs are invalid in HTML and can cause unexpected behavior with JavaScript or CSS targeting.
内容的提问来源于stack exchange,提问作者deltasierra96
相关产品推荐
相关产品推荐

