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

问题描述 投票:0回答:2
javascript html variables
2个回答
0
投票

您的 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>


-1
投票

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>

© www.soinside.com 2019 - 2024. All rights reserved.