这里我用php制作了一个示例程序。其中我包含了java脚本并使用了日期,但每次都得到相同的日期。让我们看看代码。
<?php
?>
<html>
<head>
<title>my app</title>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var time1=new Date();
var time_stack=new Array();
var time;
$(this).mousemove(function(){
time=time1.getSeconds();
alert(time1);
});
});
</script>
</head>
<body>
<h2>we are on the main_session</h2>
</body>
</html>
现在的问题是,当我移动鼠标时,会弹出一个警告框,并且显示的日期始终相同。请让我知道的问题
试试这个
$(document).ready(function(){
$(this).mousemove(function(){
var time1=new Date();
time=time1.getSeconds();
alert(time);
});
});
希望它能帮助
Hi,您应该在mousemove()
函数中为time1
变量赋值。像这样使用:
$(this).mousemove(function(){
var time1 = new Date();
var time_stack = new Array();
var time;
time = time1.getSeconds();
alert(time1);
});
这是因为当页面加载时,time1只计算一次,在每次鼠标事件中,您只会得到初始化后的秒数
变量time1
从未更改,Date
对象是相同的,所以您总是得到相同的时间?
您必须更新每次鼠标移动的日期,或者只获得一个新的Date
对象:
<html>
<head>
<title>my app</title>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(this).mousemove(function(){
var time1 = new Date();
console.log( time1.getSeconds() );
});
});
</script>
</head>
<body>
<h2>we are on the main_session</h2>
</body>
</html>
FIDDLE
实例化的Date对象不是一个秒表,当你调用它的方法时,它会得到当前时间。你需要在事件处理程序中实例化一个新的Date对象。
alert(new Date().getSeconds());
印刷错误:alert(time)
,而不是time1
,并尝试这个:
$(this).mousemove(function(){
var time1=new Date();
time=time1.getSeconds();
alert(time);
});