脚本标签没有打印任何消息



在给定的代码中,我试图打印消息,但在输入后不打印任何消息。

<!DOCTYPE html>
<html>
<head>
<title>CSS</title>
</head>
<body>
<form onsubmit="return Ak()">
<input type="text" name="abinash" placeholder="abinash"  required id="q"><br><br>
<input type="submit" name="submit" value="submit">
<div id="w"></div>
</form>

<script type="text/javascript">
function Ak()
{
var y=document.getElementById("q").value;
document.getElementById("w").innerHTML="You have typed this password"+y;


}
</script>
</body>
</html>

按下提交按钮将刷新页面。event.preventDefault();使用这个关键字

<script type="text/javascript">
function Ak()
{
var y=document.getElementById("q").value;
document.getElementById("w").innerHTML="You have typed this password"+y;
event.preventDefault();
}
</script>

正常工作,但提交表单后,所有内容都消失了。您需要将event.preventDefault();添加到表单的onsubmit属性:

<!DOCTYPE html>
<html>
<head>
<title>CSS</title>
</head>
<body>
<form onsubmit="event.preventDefault(); return Ak()">
<input type="text" name="abinash" placeholder="abinash"  required id="q"><br><br>
<input type="submit" name="submit" value="submit">
<div id="w"></div>
</form>

<script type="text/javascript">
function Ak()
{
var y=document.getElementById("q").value;
document.getElementById("w").innerHTML="You have typed this password"+y;


}
</script>
</body>
</html>

event.preventDefault()

工作,只是当你点击提交按钮页面重新加载。我试过了,你可以通过添加e.p preventdefault()来修复它;将(e)作为函数中的参数,如下所示:

<!DOCTYPE html>
<html>
<head>
<title>CSS</title>
</head>
<body>
<form onsubmit="event.preventDefault(); return Ak()">
<input type="text" name="abinash" placeholder="abinash"  required id="q"><br><br>
<input type="submit" name="submit" value="submit">
<div id="w"></div>
</form>

<script type="text/javascript">
function Ak()
{
var y=document.getElementById("q").value;
document.getElementById("w").innerHTML="You have typed this password: "+y;


}
</script>
</body>
</html>

您的代码可以工作,但是消息将消失,因为表单已成功提交。如果您希望它留在屏幕上,只需从Ak()函数返回false:

<!DOCTYPE html>
<html>
<head>
<title>CSS</title>
</head>
<body>
<form onsubmit="return Ak()">
<input type="text" name="abinash" placeholder="abinash"  required id="q"><br><br>
<input type="submit" name="submit" value="submit">
<div id="w"></div>
</form>

<script type="text/javascript">
function Ak()
{
var y=document.getElementById("q").value;
document.getElementById("w").innerHTML="You have typed this password"+y;

return false;

}
</script>
</body>
</html>

最新更新