如何在HTML和JavaScript中将多个按钮的取值拼接为单个字符串
Hey Theo, I see exactly what's going on here—your current code is replacing the inputvalue variable every time you click a button instead of adding to it. Let's fix that quickly!
The Problem
Right now, you're using inputvalue = button.value; which overwrites the existing value with the new button's value each time. That's why you only ever get a single character instead of a concatenated string like "aba".
The Solution
Instead of replacing the value, append the new character to the existing string using the += operator. We'll also set up the stop button to actually trigger a useful action (like logging your final string or resetting the input for a new session).
Here's the updated, working code:
HTML
<button value="a" type="button" onclick="buttoninput(this)"> a </button> <button value="b" type="button" onclick="buttoninput(this)"> b </button> <button value="c" type="button" onclick="buttoninput(this)"> c </button> <button value="stop" type="button" onclick="stopInput()"> Stop Input </button>
JavaScript
let inputvalue = ""; function buttoninput(button) { // Append the button's value to the existing string instead of replacing it inputvalue += button.value; console.log("Current input:", inputvalue); } function stopInput() { console.log("Final concatenated input:", inputvalue); // Optional: Uncomment below to reset the input for a new sequence // inputvalue = ""; }
How It Works
- Click "a" →
inputvaluebecomes"a" - Click "b" next →
inputvalueupdates to"ab" - Click "a" again → you'll get
"aba"—exactly the combined string you want! - The stop button logs your final result to the console, and you can enable the reset line if you want to start fresh after stopping.
That should solve your issue perfectly. Let me know if you need any further tweaks!
内容的提问来源于stack exchange,提问作者Theo

