weixin_33717298 2016-07-05 10:40 采纳率: 0%
浏览 6

jQuery 5随机图像

I've been working on a small project as of late and I'm making a list of items which users can select and purchase, right now the code that I put together displays almost every item from the folder and that lags my browser, therefore I want to make it generate only 5 random images. This is my code:

        var items_folder = "images/items/";
        $.ajax({
            url : items_folder,
            success: function (data) {
                $(data).find("a").attr("href", function (i, val) {
                    if (val.match(/\.(jpe?g|png)$/)) { 
                        $('<li><img src="' + items_folder + val + '" height="80px" width="90px"/></li>').appendTo('#items'); 
                    } 
                });
            }
        });

How would I go about doing this?

  • 写回答

1条回答 默认 最新

  • MAO-EYE 2016-07-05 11:38
    关注

    You can select five random hrefs with this

    var randomHrefs = $(data).find("a").get().sort(function() {
        return Math.round(Math.random()) - 0.5
    }).slice(0, 5);
    

    and then iterate through them (in order to display them) with

    $(randomHrefs).attr("href", function(i, val) {
        //put your logic here, as in your code
    }
    

    this question/answers helped me a lot. Check my simple demo also, it may help.

    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改