现在我正在使用java-script来显示警告消息框。它包含ok按钮,如果我点击按钮,那么只有它隐藏。但我的要求是显示它只有几秒钟,然后它应该自动关闭和重定向到我的页面。
?>
<script type="text/javascript">
alert("Enter Mandatory fields");document.location='productsegment.php';
</script>
<?
这是纯JavaScript的工作。所以流程是这样的,假设您之前输入了一个表单,其中有一个空的mandarory字段:
- 检查必填字段是否为空
- 如果是,调用一个显示警告的函数,在我们的示例中是
warn()
。最好以工具提示或模式 的形式出现。 - 有自定义的工具提示/模式隐藏后
n
秒
所以:
function warn(){
//show modal/tooltip
setTimeout(function(){
//hide modal/tooltip after 5000ms
window.location = 'productsegment.php';
},5000);
}
//call warn when you determined that mandatory field is empty
在撰写本文时,大多数其他答案基本都是错误的!
不可能在几秒钟内显示alert()
;一旦显示,只有用户交互才能关闭它。
对于应该自动关闭的消息,可以使用jQuery UI Dialog
您应该使用jQuery对话框函数而不是警报,因为它可以很容易地控制,并且您不能自动关闭警报。见下面的链接
http://dotnetguts.blogspot.fi/2012/02/how-to-open-and-auto-close-jquery-ui.html下面是来自上面链接的代码示例
<script>
$(function() {
$( "#dialog" ).dialog();
});
setTimeOut(function() {
$( "#dialog" ).dialog( "close" )
}, 5000);
</script>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
为什么不使用定时器setTimeout()