按下提交按钮后,将Javascript写在页面上

时间:2018-10-24 13:24:55

标签: javascript html function button submit

这是我从w3schools那里获得的一些代码,该代码表明,只要名称超过10个字符,页面就应该添加一些文本,在这种情况下,页面上应该加上“ hi”,但是,相反从页面中删除所有内容,然后转到新页面,仅显示“ hi”。我该如何解决?

<!DOCTYPE html>
<html>
<body>

<form action="/action_page.php" onsubmit="return myFunction()">
  Name (max 10 characters): <input type="text" id="fname" size="20" name="fname"><br>
  Age (from 1 to 100): <input type="text" id="age" size="20" name="age"><br>
  E-mail: <input type="text" id="email" size="20" name="mail"><br><br>
  <input type="submit" value="Submit"> 
</form>

<script>
function myFunction() {
    var at = document.getElementById("email").value.indexOf("@");
    var age = document.getElementById("age").value;
    var fname = document.getElementById("fname").value;
    submitOK = "true";

    if (fname.length > 10) {
        document.write("hi");
    } 

    if (isNaN(age) || age < 1 || age > 100) {
        alert("The age must be a number between 1 and 100");
        submitOK = "false";
    }

    if (at == -1) {
        alert("Not a valid e-mail!");
        submitOK = "false";
    }

    if (submitOK == "false") {
        return false;
    }
}
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

简而言之,请勿使用document.write()。如果您阅读文档顶部的漂亮的橙色文本,则会看到原因:

  

注意:当document.write写到文档时,在关闭的(已加载)文档上调用document.write会自动调用document.openwhich will clear the document

document.write()仅应在页面加载时使用,并在创建网页时输出,此后不应使用。考虑创建一个div,然后在其中写入:

function myFunction() {
    var at = document.getElementById("email").value.indexOf("@");
    var age = document.getElementById("age").value;
    var fname = document.getElementById("fname").value;
    submitOK = "true";

    if (fname.length > 10) {
        document.getElementById('result').innerHTML = 'Fname is > 10!';
    } 

    if (isNaN(age) || age < 1 || age > 100) {
        alert("The age must be a number between 1 and 100");
        submitOK = "false";
    }

    if (at == -1) {
        alert("Not a valid e-mail!");
        submitOK = "false";
    }

    if (submitOK == "false") {
        return false;
    } else {
        alert('Submitted Successfully!');
        return false; // Returning false here just for SO Code Snippet
    }
}
<form action="/action_page.php" onsubmit="return myFunction()">
  Name (max 10 characters): <input type="text" id="fname" size="20" name="fname"><br>
  Age (from 1 to 100): <input type="text" id="age" size="20" name="age"><br>
  E-mail: <input type="text" id="email" size="20" name="mail"><br><br>
  <input type="submit" value="Submit"> 
  <div id="result"></div>
</form>

此外,我注意到您正在设置submitOK = "true"。 JavaScript确实具有booleans(另请参见this)。为什么不使用它呢?

submitOK = true;

if (fname.length < 10) {
    alert('Your name should be more than 10 characters');
    submitOK = false;
}

if (submitOK) { // Same as "if (submitOK == true)"
    //Good to go
}