开发者

custom method in jquery

开发者 https://www.devze.com 2023-03-29 22:37 出处:网络
I got this code from Jquery in Action: $.fn.photoslide = function(options) { var settings = $.extend({ photoElement:\'img.photoslidePhoto\',

I got this code from Jquery in Action:

$.fn.photoslide = function(options) {
            var settings = $.extend({
                photoElement:'img.photoslidePhoto',
                transformer:function(name) {
                    return name.replace(/thumbnail/,'photo');
                },
                nextControl:null,
                previousControl:null,
                firstControl:null,
                lastControl:null,
                playControl:null,
                delay:3000
            },options||{});
$(settings.previousControl)
        .click(function() {
             showPhoto((settings.thumbnails$.length + settings.current - 1) 
                       % settings.thumbnails$.length);
                }); //Why not just use settings.current - 1??

the code is meant to be used with a slider. The slider has a button that displays the previous photo. This is the code for the showPhoto() function:

function showPhoto(index) {
                $(settings.photoElement).attr('src',settings.transformer(settings.thumbnails$[index].src));
       开发者_如何学编程         settings.current = index;
            };

            settings.thumbnail$
                .each(function(n) {
                $(this).data('photo-index',n);
                })
                .click(function() {
                    showPhoto($(this).data('photo-index'));
                }); 

My question is, why can't the index argument for showPhoto() in the click event for $(settings.previousControl) be defined simply as settings.current - 1?

I know this is a long post, but I would appreciate it very much if someone could help me understand this.


settings.thumbnails$.length is added to avoid negative indexes.

If it was not added and settings.current is 0, the result would be -1. Important to know is that applying the modulus in JavaScript does not make the number positive (unlike in other languages like Python):

> -1 % 5
  -1

It would stay -1 which eventually would result in an error if you try to access an array with it.

Adding settings.thumbnails$.length guarantees the number to be positive but does not change the result (as it is zero in the context of the modulus operator).

In case you wondered what the modulus operator [Wikipedia] is for: I assume this is used to show the photos in a loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消