0

我有一个根据此处建议的样板构建的插件:

http://markdalgleish.com/2011/05/creating-highly-configurable-jquery-plugins/

该插件在 Chrome 中按我想要的方式响应,但出现 Internet Explorer 和 FireFox 错误

您可以在此处查看正在使用的插件http://websonalized.com/myplugin.php

MSIE 开发者控制台中的错误(调试):

myplugin.js 参数无效,第 84 行字符 5

Firefox 中的错误:

错误:无用的 setTimeout 调用(参数周围缺少引号?)

setTimeout(animateSlide(sliderImage), 3000);

这是代码的相关位

...

this.$slides.each(function(i){

    slide_config = $.extend({
        duration: 3000,
        squares: 225, //it will display the closest 'perfect square' number of tiles
        transition: 'linear'
    }, $(this).data());

    var sliderImage = $(this).find('.slidebg');

    ...

    setTimeout(animateSlide(sliderImage), 3000);

    function animateSlide(s){
        console.log('ANIMATED IMAGE SLIDER ' + i);
        console.log(s); 

        $(s).show('explode', { pieces: slide_config.squares }, 5000);
    };

    ...

如果我将 setTimeout 位重写为

...

this.$slides.each(function(i){

    slide_config = $.extend({
        duration: 3000,
        squares: 225, //it will display the closest 'perfect square' number of tiles
        transition: 'linear'
    }, $(this).data());

    var sliderImage = $(this).find('.slidebg');

    ...

    setTimeout(function(){$(sliderImage).show('explode', { pieces: slide_config.squares }, 5000);}, 3000);              


    ...

但是slide_config.squares的值与this实例不对应,而是上一张幻灯片数据设置的值

this.$slides.each(function(i){

    slide_config = $.extend({
        duration: 3000,
        squares: 225, //it will display the closest 'perfect square' number of tiles
        transition: 'linear'
    }, $(this).data());

我想这与上下文有关。谁能帮我修复并了解我应该如何使用 setTimeoff?

修复意味着我能够在浏览器 FF、IE 和 Chrome 中设置无错误的 setTimeout,而每个实例的 slide_config.squares 值等于每个幻灯片对象设置的值或默认值(即 slide_default )

注意:对于第一个代码示例,slide_config.squares 的值是我所期望的,即根据幻灯片对象或 slide_config 默认值设置。同样,该代码在谷歌浏览器中似乎可以正常工作,并且具有第一位代码

4

1 回答 1

1

您需要通过编写slide_config在回调中声明为局部变量each()

var slide_config = ...;

这将为每个setTimeout闭包提供其自己的变量副本,而不是让它们都共享一个全局变量。

于 2012-09-24T03:09:28.510 回答