编程新手求助:实现多表格动态添加的颜色切换及四次点击停止功能
Solution
Here's a complete implementation that meets your requirements, with clear comments to help you understand each part:
HTML Structure
<select id="tableType"> <option value="Single">Single</option> <option value="Multiple">Multiple</option> </select> <button id="addTableBtn">Add Table</button> <div id="tableContainer"></div>
jQuery Code
$(document).ready(function() { // Track number of valid clicks (when "Multiple" is selected) let clickCount = 0; // Array of distinct background colors for new tables const tableColors = ['#f0f8ff', '#ffe4e1', '#e6e6fa', '#fffacd']; // Color to apply when stopping on the fourth click const finalModifyColor = '#ffcccb'; $('#addTableBtn').click(function() { // Check if "Multiple" option is selected const selectedType = $('#tableType').val(); if (selectedType !== 'Multiple') { return; // Exit if not the right option } // Handle first three clicks: add tables with different colors if (clickCount < 3) { // Create table HTML with current color const newTable = ` <table style="background-color: ${tableColors[clickCount]}; margin: 10px 0; border-collapse: collapse; border: 1px solid #ccc;"> <tr><th style="padding: 8px;">Column 1</th><th style="padding: 8px;">Column 2</th></tr> <tr><td style="padding: 8px;">Sample Data</td><td style="padding: 8px;">Sample Data</td></tr> </table> `; // Append the new table to the container $('#tableContainer').append(newTable); clickCount++; } // Handle fourth click: stop adding, modify the last table's color else if (clickCount === 3) { // Change background color of the most recently added table $('#tableContainer table:last').css('background-color', finalModifyColor); clickCount++; // Optional: Disable the button to prevent further clicks $(this).prop('disabled', true).text('Max Tables Added'); } }); });
Key Explanations
- Click Tracking: The
clickCountvariable keeps track of how many times we've successfully added tables (only when "Multiple" is selected). - Color Variation: The
tableColorsarray provides unique background colors for each new table added in the first three clicks. - Dropdown Validation: We only execute the table logic if the "Multiple" option is chosen—no action happens for other selections.
- Fourth Click Behavior: On the fourth click, we stop adding new tables and instead modify the background color of the last table. The button is also disabled to prevent further interactions.
内容的提问来源于stack exchange,提问作者Muhammad muzammil
相关产品推荐
相关产品推荐

