我已将我的网站设置为使用gitter弹出系统。 javascript看起来像这样:
$(document).ready(function(){
setTimeout(function() {
$.gritter.add({
title: 'Welcome!',
text: 'This appears to be your first time playing. Blablabla',
time: '25000'
});
}, 500);
setTimeout(function() {
$.gritter.add({
title: 'Walkthrough',
text: 'A walkthrough was setup ...',
time: ''
});
}, 30000);
setTimeout(function() {
$.gritter.add({
title: 'You got mail',
text: 'You have received a message from x ',
time: ''
});
}, 36000);
这是3个弹出窗口的示例。我想要做的是有这样的数组:
$popup_title[0] = "Welcome!";
$popup_text[0] = "This appears to be ...");
$popup_time[0] = 25000;
$popup_title[1] = "Walkthrough";
$popup_text[1] = "A basic blabla ...");
$popup_time[1] = "";
循环遍历此数组(如果它们不是空的)并根据数组构造javascript。
答案 0 :(得分:2)
这样的事情应该做的工作
<?php
$popups = array();
foreach ( $popup_title as $key => $title )
{
$popups[$key] = new stdClass();
$popups[$key]->title = $title;
}
foreach ( $popup_text as $key => $text )
{
$popups[$key]->text = $text;
}
foreach ( $popup_time as $key => $time )
{
$popups[$key]->time = $time;
}
?>
<script type="text/javascript">
$(document).ready(function(){
<?php foreach ( $popups as $popup ): ?>
setTimeout(function() {
$.gritter.add(<?php echo json_encode($popup);?>);
}
<?php endforeach; ?>
}
</script>
答案 1 :(得分:1)
只需回显PHP创建的JavaScript代码。
答案 2 :(得分:0)
使用多个数组有点麻烦,尝试使用嵌套数组,并确保正确地在javascript中转义输出(为清楚起见,我在下面不这样做。)
$popups = array(
array( 'title' => 'First Title', 'text' => 'First Text', 'time' => 25000 ),
array( 'title' => 'Second Title', 'text' => 'Second Text', 'time' => 2000 ),
);
echo "<script>";
foreach($popups as $idx=>$popup) {
echo "setTimeout(function() { $.gritter.add({"
."title: '{$popup['title']}',"
."text: '{$popup['text']}',"
."time: ''"
."}); }, {$popup['time']}";
}
echo "</script>";