简体   繁体   中英

javascript slideshow array

I'm using slideshow 2 (http://www.electricprism.com/aeron/slideshow/) to show a couple of pictures on my website, the problem is number of images and their locations should be hard coded into the javascript code.

i want to use an array (from a php file output) and somehow assign new values to the "var data" so that all of my images in the folder will be shown without the need to manually update each time. any ideas?

<script>
        window.addEvent('domready', function(){


            var data = { '5.jpg': { caption: '1' }, '2.jpg': { caption: '2' }, '3.jpg': { caption: '3' }, '4.jpg': { caption: '4' }};

            new Slideshow('overlap', data, { captions: { delay: 1000 }, delay: 3000, height: 300, hu: 'images/', width: 400 });

        });
    </script>

if you use PHP then you can easily do this.

say, you have logic that gets all your files into an array that looks like this:

$foo = Array("2.jpg" => "2", "3.jpg" => "3");

representing the filename and the caption

you can then do:

<?php echo json_encode($foo); ?>

to output it.

if you were to output it inside a js block into a variable:

var data = <?php echo json_encode($foo); ?>;

wich should actually render as:

var data = [{"2.jpg": "2"},{"3.jpg": "3"}];

Also, keep in mind in your example, you don't actually use an array, you use an Object. There's a substantial difference. In the output I suggest you will get an Array of Objects. You'd loop it like so:

Array.each(data, function(img) {

});

but because your keys are dynamic, it makes for difficult iteration, you need to Object.each or Object.keys or for (var key in obj) {} to get the properties. A better data structure would be:

$foo = Array(Array("name" => "2.jpg", "caption" => "two"), Array("name" => "3.jpg", "caption" => "three"));

which means in your js loop, you can reference:

Array.each(data, function(img) {
    img.name; // filename
    img.caption; // title    
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM