0

我有一些 jQuery 使用 BX 滑块为未知数量的画廊创建幻灯片。标记由 PHP CMS 输出,因此我们无法确定页面上需要多少画廊。

$(function () {

    // Use a class rather than an ID
    var $slider = $('.gallery');

    // For each result
    $slider.each(function (index, element) {

        // If there is more than 1 image
        if ($(element).find('img').length > 1) {

            // Initialise a slider using the current index value
            $slider.eq(index).bxSlider({
                auto: false,
                pager: false,
                duration: 500
            });

        }

    });

});

为了使用公共函数,我需要将 BX 滑块的每个实例定义为一个变量。

var slider = $('#gallery').bxSlider();将是常态。如何在每个语句中动态生成这些变量?

4

1 回答 1

1

你在寻找这样的东西吗?

$(function () {

    var bxSliderInstances = {};

    // Use a class rather than an ID
    var $slider = $('.gallery');

    // For each result
    $slider.each(function (index, element) {

        // If there is more than 1 image
        if ($(element).find('img').length > 1) {

            // Initialise a slider using the current index value
            bxSliderInstances["slider" + index] = $slider.eq(index).bxSlider({
                auto: false,
                pager: false,
                duration: 500
            });

        }

    });

});

bxSliderInstances将包含所有滑块实例作为关联数组,您可以根据需要使用它。

例如bxSliderInstances.slider1or`bxSliderInstances["slider1"]会给你第一个bxSlider实例。

于 2012-02-16T16:37:04.313 回答