如何用JavaScript/JQuery将Select2多选数据生成商品颜色与尺码组合表格
Got it, let's sort this out! You need to create a table that displays every possible combination of your selected colors and sizes—here are two straightforward approaches using vanilla JavaScript and jQuery, which will produce exactly the table structure you're expecting.
First, a quick note:
Make sure your array values are properly quoted (since Red and Black are strings, not variables). So your initial data should look like this:
var color = ['Red', 'Black']; var size = [41, 42, 43];
Vanilla JavaScript Approach
This uses plain JS without any libraries, great if you don't want to rely on jQuery:
// Your corrected data var color = ['Red', 'Black']; var size = [41, 42, 43]; // Get the container where you want to insert the table (add this div to your HTML: <div id="table-container"></div>) const container = document.getElementById('table-container'); // Create the table element const table = document.createElement('table'); table.setAttribute('border', '1'); // Optional: adds borders for visibility // Create the header row const headerRow = document.createElement('tr'); headerRow.innerHTML = '<th>Color</th><th>Size</th>'; table.appendChild(headerRow); // Loop through each color, then each size to create all combinations color.forEach(currentColor => { size.forEach(currentSize => { const row = document.createElement('tr'); row.innerHTML = `<td>${currentColor}</td><td>${currentSize}</td>`; table.appendChild(row); }); }); // Add the table to your page container.appendChild(table);
jQuery Approach
If you're already using jQuery in your project, this is a more concise option:
// Your corrected data var color = ['Red', 'Black']; var size = [41, 42, 43]; // Build the table HTML string let tableHtml = '<table border="1"><tr><th>Color</th><th>Size</th></tr>'; // Use nested jQuery each loops to generate all combination rows $.each(color, function(index, currentColor) { $.each(size, function(index, currentSize) { tableHtml += `<tr><td>${currentColor}</td><td>${currentSize}</td></tr>`; }); }); // Close the table tag tableHtml += '</table>'; // Insert the table into your container (make sure you have <div id="table-container"></div> in your HTML) $('#table-container').html(tableHtml);
Both approaches will generate the exact table structure you specified, with every color paired with every size. Just add the <div id="table-container"></div> to your HTML where you want the table to appear.
内容的提问来源于stack exchange,提问作者Rowkaha

