如何实现textarea值与指定h1元素内容的拼接更新?
Got it, let's fix up that function and get your desired behavior working properly. Here's a complete, robust implementation that handles edge cases like empty input too:
Full Working Code
<!-- Your existing HTML elements --> <h1 id="team_title"> Team name </h1> <textarea class="form-control" id="projectname" placeholder="Enter project name..."></textarea> <!-- Optional button to trigger the update --> <button onclick="myFunction()">Update Team Title</button> <script> // Save the original team title once, so we don't end up with repeated "-" strings const originalTeamTitle = document.getElementById('team_title').textContent.trim(); function myFunction() { // Get the textarea value and clean up extra whitespace const projectName = document.getElementById('projectname').value.trim(); const teamTitleElement = document.getElementById('team_title'); // Handle both filled and empty input cases if (projectName) { // Concatenate in the requested format teamTitleElement.textContent = `${originalTeamTitle} - ${projectName}`; } else { // Reset to original title if input is empty teamTitleElement.textContent = originalTeamTitle; } } // Optional: Auto-update as the user types (no button needed) document.getElementById('projectname').addEventListener('input', myFunction); </script>
Key Details & Fixes For Your Original Code
Save the Original Title
I added a constant to store the initial<h1>text upfront. This prevents weird repeated concatenation (likeTeam name - china123 - newProject) if you run the function multiple times.Handle Empty Input
If the user clears the textarea, the title resets to the originalTeam nameinstead of leaving a stray-at the end.Use
textContentInstead ofinnerHTML
Since we're only dealing with plain text,textContentis safer (avoids XSS risks) and more reliable thaninnerHTML.Clean Up Whitespace
Thetrim()method removes extra spaces from both the original title and user input, keeping the final result neat.Optional Real-Time Update
The extra event listener lets the title update automatically as the user types, no button click required. You can remove this if you prefer the button-triggered version.
内容的提问来源于stack exchange,提问作者Pedro Martins

