模块内的简单函数调用,得到 NaN,是吗?

发布于 2024-10-16 02:34:25 字数 7603 浏览 1 评论 0原文

这是我正在开发的模块:

var FeatureRotator = (function($,global) {
    var self = {},
        currentFeature = 0,
        images = [],
        imagePrefix = "/public/images/features/",
        timer = null,        
        totalImages = 0,
        initialFeature,
        interval,
        blendSpeed,
        element = null,
        img1 = null,
        img2 = null;

    function setVisibleImage(iid) {
        $("#img1").attr('src',images[iid].src).css('opacity',1);
        $("#img2").css('opacity',0);
        $(".active").removeClass("active");
        $("#f"+iid).addClass("active");
    }

    function setCurrentImage(id) {
        currentFeature = id;
        setVisibleImage(id);
    }

    function doHoverIn(position) {
        if (currentFeature === position) {
            self.pause();
        } else {
            setCurrentImage(global.parseInt(position, 10));
            self.pause();
        }
    }

    function doHoverOut(position) {
        self.unpause();
    }

    self.init = function(options,callback) {
        var i = 0,
            tempImg = null;

        interval = options.interval || 5000;
        blendSpeed = options.blendSpeed || 500;
        element = options.element;
        initialFeature = options.initialFeature || 0;
        img1 = $("<img/>").attr('id','img1');
        img2 = $("<img/>").attr('id','img2').css('opacity','0').css('margin-top',-options.height);

        $(element).append(img1).append(img2);

        totalImages = $(".feature").size();

        for (i = 0;i < totalImages; i++) {
            tempImg = new global.Image();
            tempImg.src = imagePrefix +"feature_" + i + ".png";
            images.push(tempImg);


            $("#f"+i).css('background-image',
                            'url("'+imagePrefix+"feature_"+i+"_thumb.png"+'")')
                     .hover(doHoverIn($(this).attr('position'))
                     , doHoverOut($(this).attr('position'))
                     ).attr('position',i);
        }

        setVisibleImage(initialFeature);

        if (options.autoStart) {
            self.start();
        }
        if (callback !== null) {
            callback();
        }
    };

    function updateImage() {        
        var active = $("#img1").css('opacity') === 1 ? "#img1" : "#img2";
        var nextFeature = (currentFeature === totalImages-1 ? 0 : currentFeature+1);

        if (active === "#img1") {
            $("#img2").attr('src',images[nextFeature].src);            
            $("#img2").fadeTo(blendSpeed, 1);            
            $("#img1").fadeTo(blendSpeed, 0);
        } else {
            $("#img1").attr('src',images[nextFeature].src);            
            $("#img1").fadeTo(blendSpeed, 1);            
            $("#img2").fadeTo(blendSpeed, 0);
        }

        $("#f"+currentFeature).removeClass("active");
        $("#f"+nextFeature).addClass("active");

        currentFeature = nextFeature;
    }



    self.start = function() {
        currentFeature = initialFeature;
        setVisibleImage(currentFeature);
        timer = global.setInterval(function(){
            updateImage();
        }, interval);
    };        

    self.pause = function() {
        global.clearTimeout(timer);
    };

    self.unpause = function() {
        timer = global.setInterval(function(){
            updateImage();
        }, interval);
    };


    return self;
}(this.jQuery, this));

下面是它在页面上的使用方式:

<script type="text/javascript">
        // ...

        $(function() {
            FeatureRotator.init({
                interval:5000,
                element:'#intro',
                autoStart:true,
                height:177,
                blendSpeed:1000,
                initialFeature:0
            });
        });
    </script>

问题是,当从 init 方法调用 setVisibleImage 时,iid 的值为 NaN。我已经单步执行了调试器,并验证了调用 setVisibleImage 函数时“initialFeature”为 0,但遗憾的是,该值并没有在那里。

谁能帮我确定问题是什么?我已经通过 JSLint 运行了代码,结果干净了。

更新

好的,这是我更新的代码,现在可以工作,除了淡入淡出不起作用,图像只是翻转到下一张并且不再平滑淡出:

var FeatureRotator = (function($,global) {
    var self = {},
        currentFeature = 0,
        images = [],
        imagePrefix = "/public/images/features/",
        timer = null,        
        totalImages = 0,
        initialFeature = 0,
        interval,
        blendSpeed;


    function setVisibleImage(iid) {
        $("#img1").attr('src',images[iid].src).css('opacity',1);
        $("#img2").css('opacity',0);
        $(".active").removeClass("active");
        $("#f"+iid).addClass("active");
    }

    function setCurrentImage(id) {
        currentFeature = id;
        setVisibleImage(id);
    }

    function doHoverIn(obj) {
        var position = global.parseInt(obj.target.attributes["position"].value,10);

        if (currentFeature === position) {
            self.pause();
        } else {
            setCurrentImage(global.parseInt(position, 10));
            self.pause();
        }
    }

    function doHoverOut() {
        self.unpause();
    }

    self.init = function(options,callback) {
        var i = 0,
            tempImg = null,
            element = null,
            img1 = null,
            img2 = null;

        interval = options.interval || 5000;
        blendSpeed = options.blendSpeed || 500;
        element = options.element;
        initialFeature = options.initialFeature || 0;
        img1 = $("<img/>").attr('id','img1');
        img2 = $("<img/>").attr('id','img2').css('opacity','0').css('margin-top',-options.height);

        $(element).append(img1).append(img2);

        totalImages = $(".feature").size();

        for (i = 0;i < totalImages; i++) {
            tempImg = new global.Image();
            tempImg.src = imagePrefix +"feature_" + i + ".png";
            images.push(tempImg);


            $("#f"+i).css('background-image','url("'+imagePrefix+"feature_"+i+"_thumb.png"+'")')
                     .hover(doHoverIn, doHoverOut)
                     .attr('position',i);
        }

        setVisibleImage(initialFeature);

        if (options.autoStart) {
            self.start();
        }
        if (typeof callback === "function") {
            callback();
        }
    };

    function updateImage() {        
        var active = $("#img1").css('opacity') === 1 ? "#img1" : "#img2";
        var nextFeature = (currentFeature === totalImages-1 ? 0 : currentFeature+1);

        if (active === "#img1") {
            $("#img2").attr('src',images[nextFeature].src);            
            $("#img2").fadeTo(blendSpeed, 1);            
            $("#img1").fadeTo(blendSpeed, 0);
        } else {
            $("#img1").attr('src',images[nextFeature].src);            
            $("#img1").fadeTo(blendSpeed, 1);            
            $("#img2").fadeTo(blendSpeed, 0);
        }

        $("#f"+currentFeature).removeClass("active");
        $("#f"+nextFeature).addClass("active");

        currentFeature = nextFeature;
    }



    self.start = function() {
        currentFeature = initialFeature;
        setVisibleImage(currentFeature);
        timer = global.setInterval(function(){
            updateImage();
        }, interval);
    };

    self.stop = function() {
        global.clearTimeout(timer);
    };

    self.pause = function() {
        global.clearTimeout(timer);
    };

    self.unpause = function() {
        timer = global.setInterval(function(){
            updateImage();
        }, interval);
    };


    return self;
}(this.jQuery, this));

Here is the module i am working on:

var FeatureRotator = (function($,global) {
    var self = {},
        currentFeature = 0,
        images = [],
        imagePrefix = "/public/images/features/",
        timer = null,        
        totalImages = 0,
        initialFeature,
        interval,
        blendSpeed,
        element = null,
        img1 = null,
        img2 = null;

    function setVisibleImage(iid) {
        $("#img1").attr('src',images[iid].src).css('opacity',1);
        $("#img2").css('opacity',0);
        $(".active").removeClass("active");
        $("#f"+iid).addClass("active");
    }

    function setCurrentImage(id) {
        currentFeature = id;
        setVisibleImage(id);
    }

    function doHoverIn(position) {
        if (currentFeature === position) {
            self.pause();
        } else {
            setCurrentImage(global.parseInt(position, 10));
            self.pause();
        }
    }

    function doHoverOut(position) {
        self.unpause();
    }

    self.init = function(options,callback) {
        var i = 0,
            tempImg = null;

        interval = options.interval || 5000;
        blendSpeed = options.blendSpeed || 500;
        element = options.element;
        initialFeature = options.initialFeature || 0;
        img1 = $("<img/>").attr('id','img1');
        img2 = $("<img/>").attr('id','img2').css('opacity','0').css('margin-top',-options.height);

        $(element).append(img1).append(img2);

        totalImages = $(".feature").size();

        for (i = 0;i < totalImages; i++) {
            tempImg = new global.Image();
            tempImg.src = imagePrefix +"feature_" + i + ".png";
            images.push(tempImg);


            $("#f"+i).css('background-image',
                            'url("'+imagePrefix+"feature_"+i+"_thumb.png"+'")')
                     .hover(doHoverIn($(this).attr('position'))
                     , doHoverOut($(this).attr('position'))
                     ).attr('position',i);
        }

        setVisibleImage(initialFeature);

        if (options.autoStart) {
            self.start();
        }
        if (callback !== null) {
            callback();
        }
    };

    function updateImage() {        
        var active = $("#img1").css('opacity') === 1 ? "#img1" : "#img2";
        var nextFeature = (currentFeature === totalImages-1 ? 0 : currentFeature+1);

        if (active === "#img1") {
            $("#img2").attr('src',images[nextFeature].src);            
            $("#img2").fadeTo(blendSpeed, 1);            
            $("#img1").fadeTo(blendSpeed, 0);
        } else {
            $("#img1").attr('src',images[nextFeature].src);            
            $("#img1").fadeTo(blendSpeed, 1);            
            $("#img2").fadeTo(blendSpeed, 0);
        }

        $("#f"+currentFeature).removeClass("active");
        $("#f"+nextFeature).addClass("active");

        currentFeature = nextFeature;
    }



    self.start = function() {
        currentFeature = initialFeature;
        setVisibleImage(currentFeature);
        timer = global.setInterval(function(){
            updateImage();
        }, interval);
    };        

    self.pause = function() {
        global.clearTimeout(timer);
    };

    self.unpause = function() {
        timer = global.setInterval(function(){
            updateImage();
        }, interval);
    };


    return self;
}(this.jQuery, this));

And here is how it is used on the page:

<script type="text/javascript">
        // ...

        $(function() {
            FeatureRotator.init({
                interval:5000,
                element:'#intro',
                autoStart:true,
                height:177,
                blendSpeed:1000,
                initialFeature:0
            });
        });
    </script>

The problem is, when setVisibleImage is called from the init method, the value of iid is NaN. I've stepped through the debugger and verified that 'initialFeature' is 0 when the setVisibleImage function is called, but alas, the value doesn't make it over there.

Can anyone help me determine what the problem is? I've run the code through JSLint, and it came back clean.

UPDATE

Ok here is my updated code, which works now except the fading doesnt work, the image just flips to the next one and doesn't fade smoothly anymore:

var FeatureRotator = (function($,global) {
    var self = {},
        currentFeature = 0,
        images = [],
        imagePrefix = "/public/images/features/",
        timer = null,        
        totalImages = 0,
        initialFeature = 0,
        interval,
        blendSpeed;


    function setVisibleImage(iid) {
        $("#img1").attr('src',images[iid].src).css('opacity',1);
        $("#img2").css('opacity',0);
        $(".active").removeClass("active");
        $("#f"+iid).addClass("active");
    }

    function setCurrentImage(id) {
        currentFeature = id;
        setVisibleImage(id);
    }

    function doHoverIn(obj) {
        var position = global.parseInt(obj.target.attributes["position"].value,10);

        if (currentFeature === position) {
            self.pause();
        } else {
            setCurrentImage(global.parseInt(position, 10));
            self.pause();
        }
    }

    function doHoverOut() {
        self.unpause();
    }

    self.init = function(options,callback) {
        var i = 0,
            tempImg = null,
            element = null,
            img1 = null,
            img2 = null;

        interval = options.interval || 5000;
        blendSpeed = options.blendSpeed || 500;
        element = options.element;
        initialFeature = options.initialFeature || 0;
        img1 = $("<img/>").attr('id','img1');
        img2 = $("<img/>").attr('id','img2').css('opacity','0').css('margin-top',-options.height);

        $(element).append(img1).append(img2);

        totalImages = $(".feature").size();

        for (i = 0;i < totalImages; i++) {
            tempImg = new global.Image();
            tempImg.src = imagePrefix +"feature_" + i + ".png";
            images.push(tempImg);


            $("#f"+i).css('background-image','url("'+imagePrefix+"feature_"+i+"_thumb.png"+'")')
                     .hover(doHoverIn, doHoverOut)
                     .attr('position',i);
        }

        setVisibleImage(initialFeature);

        if (options.autoStart) {
            self.start();
        }
        if (typeof callback === "function") {
            callback();
        }
    };

    function updateImage() {        
        var active = $("#img1").css('opacity') === 1 ? "#img1" : "#img2";
        var nextFeature = (currentFeature === totalImages-1 ? 0 : currentFeature+1);

        if (active === "#img1") {
            $("#img2").attr('src',images[nextFeature].src);            
            $("#img2").fadeTo(blendSpeed, 1);            
            $("#img1").fadeTo(blendSpeed, 0);
        } else {
            $("#img1").attr('src',images[nextFeature].src);            
            $("#img1").fadeTo(blendSpeed, 1);            
            $("#img2").fadeTo(blendSpeed, 0);
        }

        $("#f"+currentFeature).removeClass("active");
        $("#f"+nextFeature).addClass("active");

        currentFeature = nextFeature;
    }



    self.start = function() {
        currentFeature = initialFeature;
        setVisibleImage(currentFeature);
        timer = global.setInterval(function(){
            updateImage();
        }, interval);
    };

    self.stop = function() {
        global.clearTimeout(timer);
    };

    self.pause = function() {
        global.clearTimeout(timer);
    };

    self.unpause = function() {
        timer = global.setInterval(function(){
            updateImage();
        }, interval);
    };


    return self;
}(this.jQuery, this));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遗忘曾经 2024-10-23 02:34:26

既然你得到了NaN,我猜它实际上是从这一行发生的:

.hover(doHoverIn($(this).attr('position'))

...它调用了这个:

setCurrentImage(global.parseInt(position, 10)); // note the parseInt()

...它调用了这个:

setVisibleImage(id);

所以位置 传递给 parseInt 的值来自 $(this).attr('position'),这可能是一个无法解析为 Number 的值,因此你得到NaN

检查 for 语句块第一行中该属性的值。

for (i = 0;i < totalImages; i++) {
    console.log( $(this).attr('position') ); // verify the value of position
    // ...

Since you're getting NaN, I'm guessing it is actually taking place from this line:

.hover(doHoverIn($(this).attr('position'))

...which calls this:

setCurrentImage(global.parseInt(position, 10)); // note the parseInt()

...which calls this:

setVisibleImage(id);

So the position being passed to parseInt is coming from $(this).attr('position'), which is likely an value that can't be parsed into a Number, so you get NaN.

Check out the value of that attribute in first line of the block for the for statement.

for (i = 0;i < totalImages; i++) {
    console.log( $(this).attr('position') ); // verify the value of position
    // ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文