javascript - 单击 PHP/Jquery 更新附加变量

标签 javascript php jquery appendto

我有一个像这样的数组

     <?php 
        $info = array(
            "cat",
            "dog",
            "bear"
            );
    ?>

我在覆盖层上随机输出一个字符串

<script>
var text = '<?php echo $info[array_rand ($info)];?>';

$(function() {

var loading = function() {

    var over = '<div id="overlay">' + '<p class="info">' + text + '</p>' + '</div>';         
    $(over).appendTo('body');

    $('#overlay').click(function() {
        $(this).remove();
    });


    $(document).keyup(function(e) {
        if (e.which === 27) {
            $('#overlay').remove();
        }
    });
};

$('.wrapper').click(loading);

});
</script>

CSS:

#overlay {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
background: #000;
opacity: 0.90;
height: 200%;
}

.info{
position: absolute;
width: 100%;
top: 25%;
height: 200px;
font-size: 50px;
color: white;
text-align: center;
}

我的问题是: 每次通过单击正文打开覆盖层时,如何更新 var 文本并获取新的随机字符串?到目前为止,var text 中的字符串仅在我重新加载整个页面时才会更新。

谢谢:)

最佳答案

使用 JSON 在页面中打印 PHP 数组:

<!-- language: lang-php -->

<?php
$info = array(
            "cat",
            "dog",
            "bear"
            );
?>

<!-- language: lang-js -->

<script type="text/javascript">
// (it's better to retrieve it in ajax)
var arr = <?php echo json_encode($info); ?>;

//  2. Roll some dice in Javascript
// Math.random returns a random value between 0 and 1
var text = "";
// wrapped in a function so you can pick new random values
function pickRandom() {
    // Math.random returns a decimal number, and you need to access arrays using their indexes (0, 1, 2) not decimal numbers. Number.parseInt does the rounding.
    text = arr[ Number.parseInt( Math.random()*arr.length ) ];
    alert("new random value is: " + text);
}
pickRandom();
</script>

那么你的其余代码应该可以工作。希望这会有所帮助。

文档:

关于javascript - 单击 PHP/Jquery 更新附加变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28160846/

相关文章:

javascript - $scope 未定义 - codepen

javascript - 如何发送像表单数据 postman 这样的值 - React js

php - 使用前缀的 Laravel 5 路由

PHP Swatch 下载,只生成 2 种颜色?

javascript - 如何以时间间隔循环列表和淡入?

javascript - 在外部 JS 执行后加载你的 JavaScript

javascript - 如何包含/不包含 typescript 文件

php - 使用ajax提交表单后获取表单值(mysql_insert_id)

javascript - 重新解析从部分 View 创建的表单后,jQuery 提交事件未触发

javascript - w3schools 模态动画关闭