You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实时在文本中间替换显示输入值?keyup方案仅生效一次求解

Fixing Real-Time Placeholder Replacement That Only Works Once

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 name and country need to update the text).
  • On each keyup, generate the new text by replacing placeholders in the original template, then update the .email-content element 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:09:49