为4个按钮添加数值并实现列表展示及求和功能的技术问询
Got it, let's put together a simple, working implementation for your request. We'll use vanilla HTML, CSS, and JavaScript—no fancy frameworks, so it's easy to understand and adjust.
Step 1: HTML Structure
First, we'll create the buttons, a list to display added values, and a spot to show the total:
<div class="container"> <!-- Value buttons --> <button class="value-btn" data-value="100">Add 100</button> <button class="value-btn" data-value="200">Add 200</button> <button class="value-btn" data-value="300">Add 300</button> <button class="value-btn" data-value="400">Add 400</button> <!-- Sum button --> <button id="calculate-btn">Calculate Total</button> <!-- Display area for added values --> <h3>Added Values:</h3> <ul id="values-list"></ul> <!-- Total display --> <h3>Total: <span id="total-display">0</span></h3> </div>
I used data-value attributes on the value buttons to store their respective numbers—this makes it easy to grab the value without hardcoding it in multiple places.
Step 2: Basic CSS (Optional but Nice)
Let's add some simple styling to make the interface look clean:
.container { max-width: 400px; margin: 20px auto; padding: 20px; font-family: Arial, sans-serif; } .value-btn, #calculate-btn { padding: 10px 15px; margin: 5px; cursor: pointer; background-color: #4CAF50; color: white; border: none; border-radius: 4px; } #calculate-btn { background-color: #2196F3; margin-top: 10px; } #values-list { list-style-type: none; padding-left: 0; } #values-list li { padding: 5px; border-bottom: 1px solid #eee; } #total-display { color: #f44336; font-weight: bold; }
Feel free to tweak colors, spacing, or fonts to match your needs!
Step 3: JavaScript Logic
Now let's make everything work. We'll need to:
- Track the added values in an array
- Update the list when a value button is clicked
- Calculate and display the total when the sum button is clicked
// Initialize an array to store added values const addedValues = []; // Get elements from the DOM const valueButtons = document.querySelectorAll('.value-btn'); const valuesList = document.getElementById('values-list'); const calculateBtn = document.getElementById('calculate-btn'); const totalDisplay = document.getElementById('total-display'); // Add click event to each value button valueButtons.forEach(button => { button.addEventListener('click', () => { // Get the value from the data attribute and convert to number const value = parseInt(button.dataset.value); // Add to our array addedValues.push(value); // Update the displayed list updateValuesList(); }); }); // Function to update the values list function updateValuesList() { // Clear the current list valuesList.innerHTML = ''; // Add each value as a list item addedValues.forEach(value => { const li = document.createElement('li'); li.textContent = value; valuesList.appendChild(li); }); } // Add click event to calculate button calculateBtn.addEventListener('click', () => { // Calculate total using reduce() const total = addedValues.reduce((sum, current) => sum + current, 0); // Display the total totalDisplay.textContent = total; });
How it works:
- We use
querySelectorAllto grab all value buttons, then loop through them to add click handlers. - The
data-valueattribute lets us easily retrieve the button's number without repeating code for each button. - The
updateValuesListfunction clears the list and re-renders all added values every time a new one is added—simple and reliable. - For the total, we use
Array.reduce()to sum up all elements in theaddedValuesarray. If the array is empty, it'll return 0, which is perfect.
You can test this by saving all three parts into an HTML file and opening it in any browser—it'll work right away!
内容的提问来源于stack exchange,提问作者Sachintha Senanayake

