我正在研究一些代码,并尝试使用名为#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>
有谁知道如何正确地做到这一点?我不知道如何解决这个问题。 大家好!
答案 0 :(得分:0)
您在迭代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可能不是一个好主意。看看上述更改是否适合您。