JavaScript日期没有给出更新的值

3

我正在使用PHP编写一个示例程序。其中我包含了JavaScript并使用日期,但每次都得到相同的日期。让我们看一下代码。

<?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>

现在的问题是,当我移动鼠标时,会弹出一个提示框,显示的日期始终相同。请告诉我问题所在。


你不想在 onmousemove 事件中调用 alert() 函数 ;) 最好将该值显示在某个 <div> 中。 - Vivek Jain
6个回答

1

试试这个

        $(document).ready(function(){
            $(this).mousemove(function(){
                var time1=new Date();
                time=time1.getSeconds();
                alert(time);
            });
        });

希望它能有所帮助。

1

你好,你需要在 mousemove() 函数中为 time1 变量赋值。使用方法如下:

$(this).mousemove(function(){
    var time1 = new Date();
    var time_stack = new Array();
    var time;
    time = time1.getSeconds();
    alert(time1);
});

0
变量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>

代码片段


谢谢Adeneo...这些小事情让我疯狂地去找答案。 - Anurag Singh
@user1334573 - 没问题,JavaScript 中的日期有时确实会让人感到困惑。 - adeneo

0

有一个印刷错误:alert(time),而不是time1,请尝试这样做:

$(this).mousemove(function(){
                var time1=new Date();
                time=time1.getSeconds();
                alert(time);
            });

0

这是因为time1只在页面加载时被评估一次,每次鼠标事件中你只能获取从初始化时开始的秒数


0
你实例化的 Date 对象不是一个秒表,当你调用它的方法时不会得到当前时间。你需要在事件处理程序中实例化一个新的 Date 对象。
alert(new Date().getSeconds());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接