ehsan shirzadi
ehsan shirzadi

Reputation: 4859

Init an array using contents of spans

I have no Idea how to init my banner array with the text inside my spans. Do you have any Idea? Better to use javascript or JQuery?

<script language="javascript" type="text/javascript">
    var i = 1;

    function fun() {
        var banner = new Array();
        //How to init array here from inner text of spans?
        i++;
        document.getElementById("img1").src = "slide/" + banner[i] + ".jpg";
        if (i == 3) //here 2 is number of images i want to display in the slide show
        {
            i = 0;
        }
    }
    setInterval("fun()", 4000);
</script>

<div class="imagesContainer" style="display:none;">
        <span>
            73defe4b-9819-4e12-b351-3813686e0c83.gif
        </span>
        <span>
            4c2ed116-500d-42ad-8aa5-983bf214d5d3.png
        </span>
</div>

Upvotes: 0

Views: 88

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

You can use .map()

var i = 1;

function fun() {
    var banner = $('.imagesContainer span').map(function () {
        return $.trim($(this).text())
    }).get();
    //How to init array here from inner text of spans?
    i++;
    document.getElementById("img1").src = "slide/" + banner[i] + ".jpg";
    if (i == 3) //here 2 is number of images i want to display in the slide show
    {
        i = 0;
    }
}
setInterval("fun()", 4000);

jQuery(function () {
    var i = 0;
    var banner = $('.imagesContainer span').map(function () {
        return $.trim($(this).text())
    }).get();

    function fun() {
        //How to init array here from inner text of spans?
        i++;
        if (i == banner.length) {
            i = 0;
        }
        $('#img1').attr('src', '//placehold.it/128/' + banner[i])
    }
    setInterval(fun, 1000);
})

PoC: Demo

Upvotes: 2

Arnelle Balane
Arnelle Balane

Reputation: 5487

Here's how you can do it using jQuery:

var banner = [];
$('.imagesContainer span').each(function() {
  banner.push($(this).text());
});
// you can now use the banner array here

Upvotes: 0

Related Questions