javascript 如何在HTML标记中的多个位置显示变量值< p>?

brtdzjyr  于 2023-05-21  发布在  Java
关注(0)|答案(2)|浏览(167)

如何在HTML <p>标记中的多个位置返回变量值(test)。
变量在第一个示例中正确显示,但在第二个示例中为空。我做错了什么?

var name = document.querySelector("#NameInput").value;

function fillData() {
  document.querySelector("#nameOutput").innerHTML = name;
}
<p>I understand your name is <span><output id="name"></output></span>.</p>
<p>It's nice to meet you `your text`<span><output id="name"></output></span>.</p>
ehxuflar

ehxuflar1#

您的ID应该是唯一的。此外,您的HTML代码中不存在id“nameOutput”。
这里有一个快速解决方案:

<!DOCTYPE html>
<html>
<head>
    <title>Variable Output Example</title>
</head>
<body>
    <h1>Variable Output Example</h1>

    <label for="NameInput">Enter your name:</label>
    <input id="NameInput" type="text">

    <button onclick="fillData()">Submit</button>
    <p>I understand your name is <span><output id="nameOutput1"></output></span>.</p>
    <p>It's nice to meet you, <span><output id="nameOutput2"></output></span>.</p>

    <script>
        function fillData() {
            var name = document.querySelector("#NameInput").value;
            document.querySelector("#nameOutput1").innerHTML = name;
            document.querySelector("#nameOutput2").innerHTML = name;
        }
    </script>
</body>
</html>
eyh26e7m

eyh26e7m2#

const input = document.querySelector('#name-output');
input.addEventListener('input', () => 
  document.querySelectorAll('.name-output').forEach(span => span.textContent = input.value)
);
<input id="name-output"/>
<p>I understand your name is <span class="name-output"></span>.</p>
<p>It's nice to meet you `your text`<span class="name-output"></span>.</p>

相关问题