我正在编写一些代码并尝试实现一个流畅的图像网格,并使用名为 #Freewall 的查询插件执行此操作。到目前为止,这工作正常,但现在我正在尝试(已经几个小时)稍微调整脚本以从 mysql 数据库中提取图像。我实际上也得到了其中的一部分,但问题是只有第一个图像被渲染了几次。我无法弄清楚如何正确执行 while 循环 - 帮助将不胜感激。
/* These two original script code lines (below inside the comment) that replaced the background image inside the background-image attribute, pulled the image from the images folder and counted +1 – that works if images are named 1.jpg/2.jpg/3.jpg/... inside the images folder
var temp = "<div class='cell' style='width:{width}px; height: {height}px; background-image: url(images/{index}.jpg)'></div>";
html += temp.replace(/'{height'}/g, 200).replace(/'{width'}/g, w).replace("{index}", i + 1);
I edited those two lines (and included the php part) but it doesn't loop through the images, it only pulls the first image from the db and renders that 9 times which is the correct limit in the code below */
$img_sql="SELECT imglinks.artikelID, imglinks.mediasrc FROM imglinks JOIN stock ON imglinks.artikelID=stock.artikelID WHERE imglinks.artikelID=".$artIDclean; if($img_query=mysqli_query($dbconnect, $img_sql)) { $img_rs=mysqli_fetch_assoc($img_query); }
<script type="text/javascript">
<?php do {
?>
var temp= "<div class='cell' style='width:{width}px; height: {height}px; background-image: url(<?php echo $img_rs['mediasrc']; ?>)'></div>";
<?php
} while ($img_rs=mysqli_fetch_assoc($img_query));
?>
var w = 1, html = '', limitItem = 9;
for (var i = 0; i < limitItem; ++i) {
w = 200 + 200 * Math.random() << 0;
html += temp.replace(/'{height'}/g, 200).replace(/'{width'}/g, w);
}
$("#freewall").html(html);
var wall = new Freewall("#freewall");
wall.reset({
selector: '.cell',
animate: true,
cellW: 20,
cellH: 200,
onResize: function() {
wall.fitWidth();
}
});
wall.fitWidth();
// for scroll bar appear;
$(window).trigger("resize");
</script>
有谁知道如何正确地做到这一点?我不知道如何解决这个问题。谢谢伙计们!
您遍历 MySQL 查询的方式,您的变量一遍又一遍地被覆盖。尝试替换此部件:
<script type="text/javascript">
<?php do {
?>
var temp= "<div class='cell' style='width:{width}px; height: {height}px; background-image: url(<?php echo $img_rs['mediasrc']; ?>)'></div>";
<?php
} while ($img_rs=mysqli_fetch_assoc($img_query));
?>
有了这个:
<script type="text/javascript">
var temp; /* declare temp variable first */
<?php
while ($img_rs=mysqli_fetch_assoc($img_query)){
?>
/* add to the value of the temp variable while iterating through
query result rather than overwriting the value */
temp += "<div class='cell' style='width:{width}px; height: {height}px; background-image: url('<?php echo $img_rs['mediasrc']; ?>')></div>";
<?php
}
?>
/* code after this part remains unchanged */
正如评论中提到的,像这样混合和匹配PHP和JS可能不是一个好主意。查看上述更改是否适合您。