【问题标题】:Replacing input type word on button click替换按钮单击时的输入类型字
【发布时间】:2021-11-26 00:57:28
【问题描述】:

我有以下 JS 函数,如果用户输入了这个,它应该在单击按钮时将单词“hi”更改为“yo”。例如“嗨,你今天好吗?” ==> “哟,你今天好吗?”

function changeWord() {
  let str = document.getElementById('inputBox').innerHTML;
  document.getElementById('inputBox').innerHTML = str.replace("hi", "yo");;
}

当我调用 changeWord(); 时,上述内容不起作用点击后,有什么想法吗?

【问题讨论】:

  • 输入框是文本框?什么是 HTML 标记?如果它是一个文本框,它有一个值,而不是 innerHTML。
  • 就像我的 cmets 回答你的其他问题一样。带有单词边界的正则表达式可能是一个更好的主意。

标签: javascript html replace


【解决方案1】:

使用 .value 而不是 .innerHTML,如下所示:

let str = document.getElementById('inputBox').value;
document.getElementById('inputBox').value = str.replace("hi", "yo");

【讨论】:

    【解决方案2】:

    您应该以输入的值而不是 HTML 为目标。

    const input = document.querySelector('input');
    const button = document.querySelector('button');
    button.addEventListener('click', changeWord, false);
    
    function changeWord() {
      const str = input.value;
      input.value = str.replace("hi", "yo");
    }
    <input type="text" />
    <button>Click</button>

    【讨论】:

    • 请注意 OP .. 您对 str.replace 的看法——“hi”肯定会被“yo”取代——但“him”也会变成“yom”而“this”将变成“tyos”。反过来就是这样写的。 “我打招呼,她打招呼”只会改变第一次……返回“我打招呼,她打招呼”
    • 我同意@Zak,但这回答了问题。一个更强大的解决方案可能会涉及到正则表达式,它可能不在 OP 的控制范围内。
    猜你喜欢
    • 2017-08-15
    • 2012-01-12
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多