单击按钮时替换输入类型的单词

Replacing input type word on button click

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

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

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

使用 .value 而不是 .innerHTML,像这样:

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

您应该定位输入值而不是 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>