HTML/JS项目计算器开发:顾问单价与工时计算问题求助
<p> Text for Calculations Got it, let's get this project calculator working smoothly! The core issue here is that <p> elements are built for displaying content, not holding data we need to compute with. Trying to extract numbers from a <p> tag's text is error-prone (especially if you later add formatting like currency symbols), so we'll fix this by keeping our consultant rates organized in a JavaScript object—this way we can both display the rate and use it directly for calculations.
Here's a step-by-step fix with full working code:
1. First, structure your rate data clearly
We'll create a simple object that maps each consultant title to their hourly rate. This makes it easy to look up the rate whenever we need it, no text parsing required.
2. Update your functions to handle display and calculation
We'll modify the price1() function to show the rate in the <p> tag and track the selected rate for later use. We'll also add a new function to compute the total cost based on hours and the selected rate.
Full Working Code
<select style="position:absolute; left: 20%;" id="title1"> <option value="Consultant">Consultant</option> <option value="Senior Consultant">Senior Consultant</option> <option value="Principal">Principal</option> <option value="Expert Director">Expert Director</option> <option value="Partner">Partner</option> </select> <button onclick="price1()">Show Hourly Rate</button> <p id="pr1"></p> <input type="number" id="hours1" placeholder="Number of hours on the project"> <button onclick="calculateTotal()">Calculate Total Cost</button> <p id="totalCost"></p> <script> // Define consultant hourly rates in one easy-to-update place const consultantRates = { "Consultant": 150, "Senior Consultant": 220, "Principal": 300, "Expert Director": 400, "Partner": 550 }; // Track the currently selected rate for quick access let currentSelectedRate = 0; // Function to display the selected hourly rate function price1() { const titleDropdown = document.getElementById('title1'); const selectedTitle = titleDropdown.value; // Look up the rate from our object currentSelectedRate = consultantRates[selectedTitle]; // Update the <p> tag to show the formatted rate document.getElementById('pr1').textContent = `Hourly Rate: $${currentSelectedRate}`; } // Function to calculate and display total project cost function calculateTotal() { const hoursInput = document.getElementById('hours1'); const hours = parseFloat(hoursInput.value); // Validate inputs before calculating if (currentSelectedRate > 0 && !isNaN(hours) && hours > 0) { const totalCost = currentSelectedRate * hours; document.getElementById('totalCost').textContent = `Total Project Cost: $${totalCost.toFixed(2)}`; } else { document.getElementById('totalCost').textContent = "Please select a consultant title and enter valid positive hours."; } } </script>
Why this works better:
- No messy text parsing: We avoid trying to extract numbers from the
<p>tag's display text, which would break if you ever adjust how the rate is shown (like adding decimals or currency codes). - Easy updates: All rates live in one object, so you can adjust prices later without touching the display or calculation logic.
- User-friendly validation: We add checks to ensure the user has selected a title and entered valid hours, preventing confusing error results.
If you'd rather avoid using a global currentSelectedRate variable, you could also re-fetch the rate directly from the consultantRates object in the calculateTotal() function—just grab the selected title from the dropdown again and look up the rate. Either approach works great!
内容的提问来源于stack exchange,提问作者Char

