Как применить функцию JavaScript к нескольким классам div? - PullRequest
0 голосов
/ 30 марта 2012

У меня есть функция, которая создает галерею наборов flickr, извлеченных из моей учетной записи flickr. Я получаю установленные номера из базы данных и использую цикл while для отображения первого изображения из набора. Каждый элемент таблицы имеет один и тот же класс, и я применяю к ним функцию Javascript. К сожалению, каждый элемент таблицы отображает одну и ту же фотографию, последний из которых извлечен из базы данных.

$(document).ready(function() {
        var flickrUrl="";
        $('.gallery_table_data').each(function(){
                flickrUrl = $(this).attr('title');
                $('.flickr_div').flickrGallery({

                    "flickrSet" : flickrUrl,
                    "flickrKey" : "54498f94e844cb09c23a76808693730a"
                });



        });
    });

а изображения вообще не отображаются? кто-нибудь может помочь ?? Вот flickr jquery на случай, если это проблема:

var flickrhelpers = null;

(function(jQuery) {

jQuery.fn.flickrGallery = function(args) {

    var $element = jQuery(this), // reference to the jQuery version of the current DOM element
        element = this;         // reference to the actual DOM element

    // Public methods
    var methods = {
        init : function () {
            // Extend the default options
            settings = jQuery.extend({}, defaults, args);

            // Make sure the api key and setID are passed
            if (settings.flickrKey === null || settings.flickrSet === null) {
                alert('You must pass an API key and a Flickr setID');
                return;
            }



            // CSS jqfobject overflow for aspect ratio
            element.css("overflow","hidden");

            // Get the Flickr Set :)
            $.getJSON("http://api.flickr.com/services/rest/?format=json&method=flickr.photosets.getPhotos&photoset_id=" + settings.flickrSet + "&api_key=" + settings.flickrKey + "&jsoncallback=?", function(flickrData){

                var length = 1;
                var thumbHTML = '';

                for (i=0; i<length; i++) {
                    var photoURL = 'http://farm' + flickrData.photoset.photo[i].farm + '.' + 'static.flickr.com/' + flickrData.photoset.photo[i].server + '/' + flickrData.photoset.photo[i].id + '_' + flickrData.photoset.photo[i].secret +'.jpg'

                    settings.imgArray[i] = photoURL;
                    settings.titleArray[i] = flickrData.photoset.photo[i].title;
                }



                // Get the position of the element Flickr jqfobj will be loaded into
                settings.x = element.offset().left;
                settings.y = element.offset().top;
                settings.c = settings.x + (element.width() / 2);
                settings.ct = settings.y + (element.height() / 2);





                // When data is set, load first image.
                flickrhelpers.navImg(0);

            });

        }
    }

    // Helper functions here
    flickrhelpers = {
        navImg : function (index) {
            // Set the global index
            currentIndex = index;




            // Create an image Obj with the URL from array
            var thsImage = null;
            thsImage = new Image();
            thsImage.src = settings.imgArray[index];

            // Set global imgObj to jQuery img Object
            settings.fImg = $( thsImage );

            // Display the image
            element.html('');
            element.html('<img class="thsImage" src=' + settings.imgArray[index] + ' border=0>');

            // Call to function to take loader away once image is fully loaded
            $(".thsImage").load(function() {
                // Set the aspect ratio
                var w = $(".thsImage").width();
                var h = $(".thsImage").height();
                if (w > h) {
                    var fRatio = w/h;
                    $(".thsImage").css("width",element.width());
                    $(".thsImage").css("height",Math.round(element.width() * (1/fRatio)));
                } else {
                    var fRatio = h/w;
                    $(".thsImage").css("height",element.height());
                    $(".thsImage").css("width",Math.round(element.height() * (1/fRatio)));
                }

                if (element.outerHeight() > $(".thsImage").outerHeight()) {
                    var thisHalfImage = $(".thsImage").outerHeight()/2;
                    var thisTopOffset = (element.outerHeight()/2) - thisHalfImage;
                    $(".thsImage").css("margin-top",thisTopOffset+"px");
                }



                if (settings.titleArray[currentIndex] != "") {
                    $(".flickr_count").append(settings.titleArray[currentIndex]);
                }


            });


        },
        toggleUp : function() {
            $("#flickr_thumbs").slideUp("slow");
        }
    }

    // Hooray, defaults
    var defaults = {
        "flickrSet" : null,
        "flickrKey" : null,
        "x" : 0, // Object X
        "y" : 0, // Object Y
        "c" : 0, // Object center point
        "ct" : 0, // Object center point from top
        "mX" : 0, // Mouse X
        "mY" : 0,  // Mouse Y
        "imgArray" : [], // Array to hold urls to flickr images
        "titleArray" : [], // Array to hold image titles if they exist
        "currentIndex" : 0, // Default image index
        "fImg" : null, // For checking if the image jqfobject is loaded.
    }

    // For extending the defaults!
    var settings = {}

    // Init this thing
    jQuery(document).ready(function () {
        methods.init();
    });

    // Sort of like an init() but re-positions dynamic elements if browser resized.
    $(window).resize(function() {
        // Get the position of the element Flickr jqfobj will be loaded into
        settings.x = element.offset().left;
        settings.y = element.offset().top;
        settings.c = settings.x + (element.width() / 2);
        settings.ct = settings.y + (element.height() / 2);


    });



}


})(jQuery);

Ответы [ 2 ]

2 голосов
/ 30 марта 2012

Большая проблема в вашем $.each цикле. Я предполагаю, что плагин будет работать для всех элементов, над которыми вы работаете в цикле, хотя есть сомнения, что он будет работать.

Когда вы выбираете $('.flickr_div') на каждом проходе, это влияет на все элементы на странице с этим классом ... поэтому допустим только последний проход цикла

$(document).ready(function() {
        var flickrUrl="";
        $('.gallery_table_data').each(function(){
                flickrUrl = $(this).attr('title');

                /* this is your problem , is selecting all ".flickr_div" in page on each loop*/
                //$('.flickr_div').flickrGallery({

                /* without seeing your html structure am assuming 
                next class is inside "this"

                try: */

                $(this).find('.flickr_div').flickrGallery({

                    "flickrSet" : flickrUrl,
                    "flickrKey" : "54498f94e844cb09c23a76808693730a"
                });

        });
    });

РЕДАКТИРОВАТЬ Эта же концепция использования find() также должна быть преобразована в код в плагине. Плагин должен иметь все идентификаторы заменены на классы.

Плагин действительно не выглядит хорошо сконструированным для нескольких экземпляров на странице

1 голос
/ 30 марта 2012

Я могу ошибаться, но не так ли (в вашем flickrGallery объекте)

$("body").append('<div id="flickr_loader"></div>');`

создать несколько элементов с одинаковым идентификатором? И то же самое для изображений в flickrhelpers:

element.html('<img id="thsImage" src=' + settings.imgArray[index] + ' border=0>');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...