如何实时在文本中间替换显示输入值?keyup方案仅生效一次求解
Got it, I see exactly what's going wrong here. Your current code replaces the [name] placeholder in the existing text of .email-content—but once that replacement happens, the [name] string is gone forever from the element's text. So every subsequent keyup event tries to replace a placeholder that no longer exists, hence why it only works once.
Here's the fix: instead of modifying the existing text each time, we need to keep a copy of the original template (with the placeholders intact) and generate the updated text from that template every time the input changes. That way, the placeholders are always there to replace.
Step-by-Step Solution
- First, save the original template text when the page loads—this preserves the placeholders permanently.
- Listen for keyup events on both input fields (since both
nameandcountryneed to update the text). - On each keyup, generate the new text by replacing placeholders in the original template, then update the
.email-contentelement with this fresh text.
Updated Code
// Save the original template when the page loads const originalEmailTemplate = $('.email-content').text(); // Listen for keyup on both input fields $(".mailer-form input[name=person-name], .mailer-form input[name=person-country]").keyup(function(){ // Get current values (fallback to empty string if input is blank) const userName = $('input[name=person-name]').val() || ''; const userCountry = $('input[name=person-country]').val() || ''; // Generate updated text from the original template const updatedText = originalEmailTemplate .replace('[name]', userName) .replace('[country]', userCountry); // Update the content element $('.email-content').text(updatedText); })
Bonus: Handling Multiple Occurrences of Placeholders
If your template has multiple instances of [name] or [country], use a global regex replace instead of the basic replace() method (which only replaces the first match):
const updatedText = originalEmailTemplate .replace(/\[name\]/g, userName) // Global replace for all [name] .replace(/\[country\]/g, userCountry); // Global replace for all [country]
This approach ensures that every keyup event starts fresh with the original placeholder text, so your replacements will work reliably every time you type.
内容的提问来源于stack exchange,提问作者shadi

