根据URL从数组中随机显示

Display randomly from array based on URL

本文关键字:随机 显示 数组 URL 根据      更新时间:2023-09-26

我有一个图像数组,我想在页面上随机显示,但如果图像扩展名与url扩展名匹配,它应该跳过数组中的某个条目,然后转到下一个。这是我迄今为止的代码。

$(document).ready( function() {
    //$('.test a').append('<img class="img-responsive portfolio-item thumbnail" src="http://placehold.it/500x300" alt="">');
    var imgs = ["img1.png","img2.png","img3.png","img4.png",]
    for ( var n=0; n < 4; n ++){
        var goImg = 'img/' +  imgs[n];
        n = parseInt(n);
        var pItem = 'pItem' +  (n + 1);
        $('#otherProjects').append('<div class="col-sm-3 col-xs-6">
            <a href="'+pItem+'.html">
                <img class="img-responsive portfolio-item thumbnail"
                src="'+goImg+'" alt=""> 
            </a>
         </div>');              
    }
});
$(document).ready( function() {    
    function appendImages(pItem){
        var imgs = ["img1.png","img2.png","img3.png","img4.png",];
        for ( var n=0; n < 4; n ++){
            var goImg = 'img/' +  imgs[n];
            var matchImg = imgs[n].substr(0, imgs[n].lastIndexOf('.'));
            if(pItem != matchImg){
                $('#otherProjects').append('<div class="col-sm-3 col-xs-6">'+
                '<a href="'+pItem+'.html">'+
                    '<img class="img-responsive portfolio-item thumbnail"'+
                    'src="'+goImg+'" alt="">'+ 
                '</a>'+
                '</div>');              
            }
        }
    }   

    var page = window.location.pathname.split("/").pop();    //this will return "abc.html"
    appendImages(page.substr(0, page.lastIndexOf('.'))); //this will return "abc"
});

如果您调用方法"appendImages",它将发送当前页面名称(不带扩展名)。在方法内部,url名称将与数组值匹配,如果匹配,则跳过。

谢谢Raja,你的代码帮助我更接近我想要实现的目标。这是我到目前为止所拥有的,它正在按照我的需要工作,我的最后一步是让它从数组中随机选择4个项目,而不是前4个。

$(document).ready( function() {

            //array of all portfolio items
            var imgs = ["pItem1","pItem2","pItem3","pItem4","pItem5"]
            //gets the current portfolio page you are on
            var pathname = window.location.pathname.split('/').pop('');
            pathname = pathname.substr(0, pathname.lastIndexOf('.'));

            //checks the imgs array and deletes the current portfolio entry
            var imgs = $.grep(imgs, function(i){
                return(i !== pathname );
            });
            //goes through the array and appends it to the page
            for ( var n=0; n < 4; n ++){
            var imgUrl = 'img/' +  imgs[n] +'.png';
            n = parseInt(n);
            var pItem = imgs[n]
            $('#otherProjects').append('<div class="col-sm-3 col-xs-6"><a href="'+pItem+'.html"><img class="img-responsive portfolio-item thumbnail" src="'+imgUrl+'" alt=""></a></div>');
        }
});