当用户在文本框中输入内容时替换段落中的文本

当我在文本框中输入内容并提交时,我试图更改段落标记中的文本。例如,如果该段落说“橙色”,并且如果我在框中输入“橙色”,它会更改为“橙色很棒”。


function changeText() {

  let lbl = document.getElementById('change');

  let empName = document.getElementById('textbox').value;

  lbl.innerText = empName;

}

<p id="change">Apple or Orange?</p>

<input type="text" id="textbox" />

<input type="button" value="Submit" onclick="changeText()" />


慕哥9229398
浏览 99回答 1
1回答

慕的地8271018

只需添加一个 if 块来检查值是否是苹果或橙色或其他内容,然后更新段落<html><link rel="stylesheet" href="styles.css"><title>Apple or Oranges</title><body><p id="change"> Apple or Orange?</p><input type="text" id="textbox"/><input type="button" value="Submit" onclick="changeText()" /><script>&nbsp; &nbsp; function changeText() {&nbsp; &nbsp; &nbsp; &nbsp; let lbl = document.getElementById('change');&nbsp; &nbsp; &nbsp; &nbsp; let empName = document.getElementById('textbox').value;&nbsp; &nbsp; &nbsp; &nbsp; if (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; empName.toUpperCase() === 'APPLE' ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; empName.toUpperCase() === 'APPLES' ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; empName.toUpperCase() === 'ORANGE' ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; empName.toUpperCase() === 'ORANGES'&nbsp; &nbsp; &nbsp; &nbsp; ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; empName += " are awesome"&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; lbl.innerText = empName;&nbsp; &nbsp; }</script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5