如何根据eventDiv的counterID将innerHTML元素中标签文本替换为变量值
Hey there! Let's fix up your code to handle the variable substitution you need, plus address a couple of issues in the original snippet.
First, your current counterID increment will throw a NaN error because you're trying to increment a variable that hasn't been initialized yet. We'll fix that by declaring the counter outside the function so it persists across calls.
Then, using template literals (backticks) instead of string concatenation with backslashes will make it way easier to insert variables directly into your HTML. Here's how to adjust your code to replace the label text with a variable and add other variables into the innerHTML:
// Initialize counter outside the function to keep track across addRow calls let counterID = 0; function addRow() { counterID += 1; // Increment first so we start at row 1 // Example variables you want to use in your HTML const departureLabelText = `Departure #${counterID}`; // Custom label text per row const departureLocation = "Los Angeles"; // Example variable for location data const eventDiv = document.createElement('div'); eventDiv.setAttribute('id', `event-row-${counterID}`); // Unique ID with counter eventDiv.className = 'event_cont'; // Use template literals to inject variables directly into the HTML eventDiv.innerHTML = ` <div class="cont" onclick="addRow()"> <div class="dep_cont"> <div class="cont_label"> <!-- Replace label text with our variable --> <label id="dep_cont_label_${counterID}">${departureLabelText}</label> </div> <!-- Add another element using a variable --> <div class="dep_details"> <span>Origin: ${departureLocation}</span> </div> </div> </div> `; // Don't forget to append the new row to your page! // Replace document.body with your target container element if needed document.body.appendChild(eventDiv); }
Key changes explained:
- Persistent counter: Declaring
counterIDoutside the function ensures it doesn't reset toNaNand increments correctly each time you calladdRow(). - Template literals: Using backticks (
) lets you write clean, multi-line HTML and insert variables with${variableName}`—no more messy string escaping. - Unique IDs: Added the counter to both the eventDiv ID and label ID so every element has a unique identifier (critical if you need to target specific rows/labels later).
- Variable insertion: We replaced the hardcoded "Departure" text with
departureLabelTextand added a new section usingdepartureLocationto show how to inject additional variables. - DOM insertion: The original code created the div but didn't add it to the page—we added
appendChildto make sure the new row appears.
If you have specific variables you need to use (like dynamic data from a form or API), just replace the example variables with your actual data, and the template literal syntax will handle inserting them into the HTML seamlessly.
内容的提问来源于stack exchange,提问作者Cardona

