【发布时间】:2016-09-13 06:27:43
【问题描述】:
我有一个关联数组,用于生成图像。从这些图像中,我想选择两张或多张图片来随机获得一张。 我的代码有效,但我有两个问题:
如何改进我的代码? 以及如何使用 json 或其他我的网站在提交后不会刷新的东西?
<style>
.check {
opacity: 0.5;
color: #996;
}
</style>
<script>
function getRandomInt( min, max )
{
return Math.floor( Math.random() * (max - min + 1) ) + min;
}
function debug()
{
console.log( $( "img.check" )[0] );
}
$( document ).ready( function()
{
$( "form" ).submit( function()
{
var images = $( "img.check" );
if( images.length > 0 )
{
$( "input[name=images]" ).attr( "value", $( images[getRandomInt( 0, images.length )] ).data( "id" ) );
return true;
}
else
{
alert( 'Kein Bild ausgewählt.' );
return false;
}
} );
$( 'form img' ).click( function()
{
$( this ).toggleClass( 'check' );
} );
} );
</script>
</head>
<body>
<?php
$random = [
'Key1' => 'https://static.pexels.com/photos/4952/sky-beach-vacation-summer.jpeg',
'Key2' => 'https://static.pexels.com/photos/1852/dawn-landscape-mountains-nature.jpg',
'Key3' => 'https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg',
'Key4' => 'https://static.pexels.com/photos/12567/photo-1444703686981-a3abbc4d4fe3.jpeg',
'Key5' => 'https://static.pexels.com/photos/2757/books-magazines-building-school.jpg',
];
?>
<form method="post">
<input type="hidden" name="images">
<?php
foreach ($random as $key => $val)
{
echo '<h1>$key</h1>';
echo '<img src="'.$val.'" width="100px" height="100px" data-id="'.$key.'"">';
}
?>
<button type="submit" name="submit" class="btn btn-default">Submit</button>
</form>
<?php
if (isset($_POST['images']))
{
echo '<img src="' . $random[$_POST['images']] . '" />';
}
?>
【问题讨论】:
-
使用
AJAX向服务器发送数据而不刷新。 -
在 PHP 中使用
AJAX概念。 -
您也可以在加载下一组图像之前对其进行缓存。
-
查看我的更新答案。它会帮助你!
标签: javascript php jquery arrays