[英]Javascript is almost working, but it then reloads page?
so I'm hiding items until someone puts in a secret word in a form. 所以我隐藏物品,直到有人在表格中放入一个秘密词。 It actually works, but then it reloads the page. 它实际上工作,但然后它重新加载页面。 What am I missing? 我错过了什么?
You can see it here: xxx under projects and the password is '--'.
你可以在这里看到它:xxx在项目下,密码是' - '。
This is the code I'm using: 这是我正在使用的代码:
<script language="javascript">
function projectsvisible()
{
document.getElementById("myprojects").style.display = "block";
}
function projectshide()
{
document.getElementById("myprojects").style.display = "none";
}
function projectsshow()
{
if(document.getElementById("password").value=="danielle")
{
projectsvisible();
}
else { projectshide(); }
}
</script>
You are using a form with a submit button. 您正在使用带有提交按钮的表单。 This creates and fires a synchronous page reloading Http Request. 这将创建并触发重新加载Http请求的同步页面。 You should not use a form. 你不应该使用表格。 Just use a normal button with an on click handler and wrap them in a div instead. 只需使用带有单击处理程序的普通按钮,然后将它们包装在div中。
It's auto-refreshing due to the button type of submit
. 由于按钮类型的submit
它会自动刷新。 This will cause a postback to the page and refresh. 这将导致回发到页面并刷新。 There's a few workarouds: 有几个workarouds:
return false;
添加return false;
to your inline handler or function 到内联处理程序或函数 e.preventDefault
where e
is event
passed in to the parent function 使用e.preventDefault
,其中e
是传递给父函数的event
submit
to button
将按钮类型的submit
更改为button
First, change <form id="projectform" method="POST" action="#" class="form-horizontal" onsubmit="return projectsshow(); return false">
首先,更改<form id="projectform" method="POST" action="#" class="form-horizontal" onsubmit="return projectsshow(); return false">
to 至
<form id="projectform" method="POST" action="#" class="form-horizontal" onsubmit="return projectsshow();">
Then change projectsshow()
function: 然后改变projectsshow()
函数:
function projectsshow()
{
if(document.getElementById("password").value=="danielle")
{
projectsvisible();
}
else { projectshide(); }
return false;
}
Your button is what's reloading the page. 你的按钮正在重新加载页面。 You can either use jQuery's event.preventDefault() on the button, or style a div to look like a button and do your onlick action on the button. 您可以在按钮上使用jQuery的event.preventDefault(),或者将div设置为按钮,然后对该按钮执行onlick操作。
you onsubmit handler does not return false. 你onsubmit处理程序不返回false。 projectsshow() does not return false. projectsshow()不返回false。 Therefore your form is not prevented from getting submitted and so the page refresh happens. 因此,不会阻止您的表单被提交,因此页面刷新会发生。
<form id="projectform" method="POST" action="#" class="form-horizontal"
onsubmit="return projectsshow(); return false">
Either fix projectsshow()
method to return false or change onsubmit to onsubmit="projectsshow(); return false"
修复projectsshow()
方法返回false或将onsubmit更改为onsubmit="projectsshow(); return false"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.