javascript - 如何将 javascript 函数应用于多个 div 类?

标签 javascript jquery flickr

我有一个函数可以创建从我的 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);

最佳答案

最大的问题出在你的$.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()的相同概念也应该重构到插件内的代码中。插件应该将所有 ID 替换为类。

对于页面中的多个实例来说,插件的构造看起来确实不太好

关于javascript - 如何将 javascript 函数应用于多个 div 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9935542/

相关文章:

Javascript复制对象数组中的嵌套数组

javascript - 渲染主干 View 时如何防止图像闪烁?

php - select onchange中查询数据库

javascript - 如何在我的 js 代码中使用简写 if else 语句

javascript - HTML 导入不起作用...即使它受支持

JavaScript 文件观察器

javascript - meteor ,Javascript : Clean up or iterator only 10 of history

image - 托管网站图像: Flickr PRO, Amazon S3还是...?

CSS 和 Safari/Chrome

javascript - 在显示图库图像时需要有关 Flickr/JSON/Javascript 问题的帮助