根据URL从数组中随机显示

时间:2014-09-02 20:06:19

标签: javascript jquery html

我想要在我的页面上随机显示一系列图像,但是如果图像扩展名与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>');              
    }

});

2 个答案:

答案 0 :(得分:0)

$(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名称将与数组值匹配,如果匹配则跳过。

答案 1 :(得分:0)

谢谢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>');

        }

});