使用跨度内容初始化数组

时间:2014-01-20 10:46:21

标签: javascript jquery

我不知道如何在我的跨度中使用文本初始化我的横幅数组。你有什么主意吗?最好使用javascript或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>

2 个答案:

答案 0 :(得分:2)

您可以使用.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

答案 1 :(得分:0)

以下是使用jQuery的方法:

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