javascript - 当变量(时间)为0时显示div

标签 javascript php jquery

我试图在时间(从数据库导入)时显示 div - 当前时间将为 0。如何做到这一点?代码如下:

while ($row = mysqli_fetch_array($result)) {
    echo "<div class='alert' id='" . $row['id'] . "' style='display:none'><br><br><center><h2>";
    echo $row['title'];
    echo "<br><br>";
    echo $row['category'];
    echo "</h2><br><br><hr><br><br></center>";
    echo $row['description'];
    echo "</div>";
    $timeFirst  = strtotime($row['date']);
    $timeSecond = strtotime("now");
    $differenceInSeconds = $timeFirst - $timeSecond;
    if ($differenceInSeconds==0)
    {
        echo "<script>";
        echo "$(document).ready(function(){";
        echo "$('#". $row['id'] . "').show();";
        echo "$('#". $row['id'] . "').delay(15000);";
        echo "$('#". $row['id'] . "').hide();";
        echo "});";
        echo "</script>";
    }
}

最佳答案

我认为您想在 javascript 代码中添加 setTimeout() 而不是 if ($differenceInSeconds==0) {} PHP 端。

此外,您还需要重写 jQuery(有效地显示元素,不延迟任何内容并立即隐藏它)

$("#element").show();
$("#element").delay(15000);
$("#element").hide();

$("#element").show().delay(15000).hide(0);

完整代码如下。

while ($row = mysqli_fetch_array($result)) {
    echo "<div class='alert' id='" . $row['id'] . "' style='display:none'><br><br><center><h2>";
    echo $row['title'];
    echo "<br><br>";
    echo $row['category'];
    echo "</h2><br><br><hr><br><br></center>";
    echo $row['description'];
    echo "</div>";
    $timeFirst  = strtotime($row['date']);
    $timeSecond = strtotime("now");
    $differenceInSeconds = $timeFirst - $timeSecond;

    // Adding a setTimeout so your JS code actually gets written and executes when it should.
    if ($differenceInSeconds >= 0) {
        echo "<script>";
        echo "$(document).ready(function(){";
        echo "window.setTimeout(function() {";
        echo "$('#". $row['id'] . "').show().delay(15000).hide(0);";
        echo "}, " . $differenceInSeconds * 1000 . ");";
        echo "});";
        echo "</script>";
    }
}

关于javascript - 当变量(时间)为0时显示div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36979069/

相关文章:

PHP 警告 : Use of undefined constant PASSWORD_ARGON2ID when using password_hash() in php 7. 3

php - 如何自动同步mysql数据库和solr

javascript - 录音javascript

jquery - 不应使用 keydown 事件的“获取 "The ' charCode”属性。该值无意义”jQuery 中的错误

javascript - Chrome 中的粘性顶部栏渲染问题

javascript - context.fillStyle 不工作

javascript - 为什么 Redux reducer 被称为 reducer?

javascript - 代表许多数组的唯一索引的数字

php - 如何将动态创建的输入框的值插入数据库

jquery - Chrome 扩展在内容脚本中使用 jquery 解决创建对话框窗口时出现的错误