【问题标题】:pass parameter to javascript onload event from php从php将参数传递给javascript onload事件
【发布时间】:2013-06-29 23:16:26
【问题描述】:

我有一个用于倒计时的 JavaScript 代码。我有一个从数据库 usu php 收集的日期,我需要将日期对象传递给 javascript 函数,但我不知道如何。我试过这个:

<body onload="countIt(<?php echo $event->startDate;?>)">

但它似乎不起作用。这是我的js代码

function countIt(date) {
    ///i will parse the date into below variables if I can get the date.
    year = 2013;
    month = 09;
    day = 28;
    hours = 12;
    minutes = 00;
    seconds = 00;

    setTimeout(function() {
        endDate = new Date(year, month, day, hours, minutes, seconds, 00);
        thisDate = new Date();
        thisDate = new Date(thisDate.getFullYear(), thisDate.getMonth() + 1, thisDate.getDay(), thisDate.getHours(), thisDate.getMinutes(), thisDate.getSeconds(), 00, 00);

        var daysLeft = parseInt((endDate - thisDate) / 86400000);
        var hoursLeft = parseInt((endDate - thisDate) / 3600000);
        var minutsLeft = parseInt((endDate - thisDate) / 60000);
        var secondsLeft = parseInt((endDate - thisDate) / 1000);

        seconds = minutsLeft * 60;
        seconds = secondsLeft - seconds;

        minutes = hoursLeft * 60;
        minutes = minutsLeft - minutes;

        hours = daysLeft * 24;
        hours = (hoursLeft - hours) < 0 ? 0 : hoursLeft - hours;

        days = daysLeft;

        startCount(days, hours, minutes, seconds);
    }, 1000);
}

function startCount(days, hours, minutes, seconds) {
    document.getElementById("counter").innerHTML = "DAYS " + days + ", HOURS " + hours + ", MINUTES " + minutes + ", SECONDS: " + seconds;
    countIt();
}

【问题讨论】:

  • 您是否看到任何错误(检查 js 控制台)。你也可以举一个php插入的日期的例子

标签: php javascript parameter-passing


【解决方案1】:

您可以通过多种方式制作 javascript 日期对象:

    var d = new Date();
    var d = new Date(milliseconds);
    var d = new Date(dateString);
    var d = new Date(year, month, day, hours, minutes, seconds, milliseconds); 

因此,选项之一可能是:

    <body onload="countIt(<?php echo strtotime($event->startDate);?>)">

在你的函数开始时:

    var date = new Date(date);

只有当你的 $event->startDate 是有效的 PHP 日期格式时,这才有效。你可以了解更多关于HERE的信息。

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 2011-07-10
    • 2014-08-15
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    相关资源
    最近更新 更多