我是JS的新手,当用户在我的html页面中输入他/她的“姓名-邮件-消息”时,我会尝试显示一个警告框。该警告框应包含用户提供的信息。这就是我所做的;
<button type="submit" onclick="test()" class="form-control" id="submit-button" name="submit">Send</button>
<script type="text/javascript">
function test() {
let inputName = document.getElementById("cf-name");
let inputMail = document.getElementById("cf-mail");
let inputMessage = document.getElementById("cf-message");
let total = (inputName.value);
alert(inputName.value + '\n' + inputMessage.value);
}
</script>当我运行它的时候,我得到了这个输出。

如何解决此问题?如果你能帮上忙,我将不胜感激。
发布于 2021-06-28 14:41:16
您需要首先获取每个输入的.value,而不是将其应用于整个警报消息。
<input type="text" placeholder="Name" id="cf-name">
<input type="email" placeholder="Email" id="cf-mail">
<textarea placeholder="Msg" id="cf-message"></textarea>
<button type="submit" onclick="test()" class="form-control" id="submit-button" name="submit">Send</button>
<script type="text/javascript">
function test() {
let inputName = document.getElementById("cf-name");
let inputMail = document.getElementById("cf-mail");
let inputMessage = document.getElementById("cf-message");
let total = (inputName.value + '\n' + inputMail.value + '\n' + inputMessage.value);
alert(total);
}
</script>
发布于 2021-06-28 14:39:29
您正在添加DOM节点。我假设您想要将这些元素的值相加?如果是这样,访问它们的值并将其存储在变量中,如下所示:
function test() {
const inputName = document.getElementById("cf-name").value;
const inputMail = document.getElementById("cf-mail").value;
const inputMessage = document.getElementById("cf-message").value;
const total = (inputName + '\n' + inputMail + '\n' + inputMessage);
alert(total);
}一些额外的注意事项:
const而不是let,因为这些变量在稍后的代码中不会被重新赋值,因此请避免使用alert()。改为使用console.log(),并打开浏览器开发工具以检查输出发布于 2021-06-28 14:38:24
只需在警报中传递total变量
alert(total)https://stackoverflow.com/questions/68158586
复制相似问题