Javascript 多次使用文本框值更新网页上的文本
我需要在网页上显示样板文本,并让访问者能够通过在文本框中提交值来更新文本。我有两个问题:Javascript 多次使用文本框值更新网页上的文本,javascript,html,Javascript,Html,我需要在网页上显示样板文本,并让访问者能够通过在文本框中提交值来更新文本。我有两个问题: 我只能使用文本框值一次,但我想多次使用它。我理解这是由于使用document.getElementById造成的。我应该使用document.getElementByClassName,但是我很难做到这一点 我希望在样板文本中包含一个默认值,然后用文本框中的值替换该值。例如,“您的公司”将替换为“XYZ公司”(或用户在文本框中提交的任何内容) 我有以下代码: <!DOCTYPE html> &l
<!DOCTYPE html>
<html>
<body style="text-align:center;">
Company Name:
<input type="text"
id="myText"
value="">
<button type="button"
onclick="myFunction()">
Submit
</button>
<p>I would like to use the name, <strong><span id="demo"></span></strong>, multiple times in this text. I'd like to use it <strong><span id="demo"></span></strong> and again <strong><span id="demo"></span></strong>.</p>
<script>
// Here the value is stored in new variable x
function myFunction() {
var x =
document.getElementById("myText").value;
document.getElementById(
"demo").innerHTML = x;
}
</script>
</body>
</html>
公司名称:
提交
我想在本文中多次使用名称。我想反复使用它
//这里的值存储在新变量x中
函数myFunction(){
变量x=
document.getElementById(“myText”).value;
document.getElementById(
“demo”).innerHTML=x;
}
我错过了什么?任何方向都值得赞赏。提前感谢。首先,您应该使用这些类,因为ID是唯一的。其次,当调用getElementById()甚至querySelector()时,您只得到与查询匹配的第一个元素。您应该为所有元素提供一个共享类,使用querySelectorAll()选择所有元素,然后对它们进行循环,如下所示:
公司名称:
提交
我想在本文中多次使用名称。我想反复使用它
//这里的值存储在新变量x中
函数myFunction(){
变量x=
document.getElementById(“myText”).value;
//选择类(“.”)为“demo”的所有元素
const allDemoElements=document.queryselectoral(“.demo”);
//循环每个元素,并更改innerHTML
allDemoElements.forEach(el=>{
el.innerHTML=x;
});
}