簡體   English   中英

單擊提交按鈕時,它只會刷新頁面。 如何獲得顯示我想要的消息的信息?

[英]When clicking on the submit button it just refreshes the page. How can I get it to display the message I desire?

<!DOCTYPE html>
<html>
<meta charset = "utf-8">
<head>
<title>Assignment 6</title>
<script type = "text/JavaScript">
function years()
{
    var yourName = document.getElementById("name").value;
    var yearBorn = document.getElementById("yearBorn").value;
    var today = new Date();
    var currentYear = today.getFullYear();
    var age = currentYear - yearBorn;
    if(age >= 0)
    {
        document.write("Hello, " +yourName+ ". You are " +age+ " years old.");
    }
    else
    {
        document.write("You are not born yet.");
    }
    document.close();
};
</script>


</head>


<body>
<form method = "post">
<p>Enter your name: <input type = "text" id = "name" size = "25" /></p>
<p>Enter year Born: <input type = "text" id = "yearBorn" size = "4" /></p>
<p><input type = "submit" value = "Click to show message" onClick = "years()" /></p>
</form>
</body>
</html>

當用戶單擊“提交”按鈕時,嘗試獲取javascript部分以顯示消息。 但是,對我來說,它只是刷新頁面,並且不輸出任何消息。

這是因為提交表單時,其默認行為是刷新頁面。 如果您實際上並不關心將數據提交到服務器,則只需進行更改

<p><input type = "submit"

<p><input type = "button"

如果您確實希望提交的數據執行以下操作:您需要使用preventDefault()

<body>
<form id="form1" method = "post" action="">
<p>Enter your name: <input type = "text" id = "name" size = "25" /></p>
<p>Enter year Born: <input type = "text" id = "yearBorn" size = "4" /></p>
<p><input id="myButton" type = "submit" value = "Click to show message"/></p>
</form>
</body>
</html>

<script>
document.getElementById("myButton").addEventListener("click",function(event){
    event.preventDefault();
    var yourName = document.getElementById("name").value;
    var yearBorn = document.getElementById("yearBorn").value;
    var today = new Date();
    var currentYear = today.getFullYear();
    var age = currentYear - yearBorn;
    if(age >= 0)
    {
    document.write("Hello, " +yourName+ ". You are " +age+ " years old.");
    }
    else
    {
    document.write("You are not born yet.");
    }
    document.close();
    document.getElementById("form1").submit();
});

您不能調用提交事件嗎?

<form name="form" method="post" onsubmit="years()"> 

您需要將輸入的類型更改為“按鈕”,而不是“表單”。 在這種情況下,您不需要提交表單,因為只需要與服務器交互即可。

這是因為您沒有我認為的形式的動作? 添加與相同的文件

<form method="post" action="index.php">

希望這可以幫助! 您可能需要在JavaScript中使用if公式來激活文件的后部(彈出窗口)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM