javascript - 如何限制我的画廊一次显示的行数

标签 javascript php jquery

我有一个使用 php 从目录生成的画廊。

我只想显示 2 行,每行 4 张图像,因此总共 8 张图像。底部会有一个“显示更多”按钮。

当用户单击按钮时,将加载另外 2 行。

如何限制行数?

jQuery 是正确的选择吗?

<div class="w3-content w3-container w3-padding-64" style="margin-top:50px;">
  <h3 class="w3-center w3-text-white">Never Ending Light of Day</h3>
  <br>

  <!-- Responsive Grid. Four columns on tablets, laptops and desktops. Will stack on mobile devices/small screens (100% width) -->
  <div class="w3-row-padding w3-center">
<?php
// Find all files in that folder
$files = glob('uploads/*');

// Do a natural case insensitive sort, usually 1.jpg and 10.jpg would come next to each other with a regular sort
natcasesort($files);


// Display images
foreach($files as $file) {
   echo '<div class="w3-col m3"><img src="' . $file . '" style="width:100%" onclick="onClick(this)" class="w3-hover-opacity"/></div>';
}

?>
    
  </div>
</div>

最佳答案

这里有两个问题:

如何限制php脚本创建的行数

你需要拼接你 $files数组 array_splice($files, 0, 8)

<?php
// Find all files in that folder
$files = glob('uploads/*');

// Do a natural case insensitive sort, usually 1.jpg and 10.jpg would come next to each other with a regular sort
natcasesort($files);

// get only 8 files
$files = array_splice($files, 0, 8);


// Display images
foreach($files as $file) {
   echo '<div class="w3-col m3"><img src="' . $file . '" style="width:100%" onclick="onClick(this)" class="w3-hover-opacity"/></div>';
}

?>

然后您可以使用 $offset 对图像列表进行“分页”可以从请求参数生成的变量:

$offset = $_GET["images_offset"] || 0; // should be a multiple of 8
$files = array_splice($files, $offset, 8);

如何在用户单击按钮时加载新图像

jQuery 可能是异步加载的方式。

var offset = 0;
var url = "yourpageurl";
$('#yourbuttonidoranyselector').bind('click', function(){
  offset += 8;
  $.ajax(url + "?images_offset=" + offset, function(data){
    // append the new lines to the chosen container
  });
});

这只是您应该探索的一点逻辑。请不要只是复制并粘贴代码。

关于javascript - 如何限制我的画廊一次显示的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37627905/

相关文章:

javascript - 添加消息到 p :growl using Javascript

javascript - 雷达图好看的JS图库有哪些?

javascript - 尝试使用特定 URL 预填充表单字段

php - 销毁php后启动 session

php - 当用户状态变为1时如何进行更新查询

JavaScript 的 lastIndexOf()

javascript - Windows系统上的ckeditor问题

javascript - 在 php 中使用 javascript 的 HTML 似乎有冲突

javascript - $(窗口)打开。 ('load' ) 函数适用于 Firefox,但不适用于 Safari/iOS 或 Chrome?

javascript - 使用 Javascript 更改动态内容的语言