【问题标题】:jQuery plugin setTimeout IE ( Internet Explorer 8 ) ErrorjQuery 插件 setTimeout IE (Internet Explorer 8) 错误
【发布时间】:2012-09-24 11:09:28
【问题描述】:

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

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 默认值设置。再次,代码似乎在谷歌浏览器中使用第一段代码运行良好

【问题讨论】:

    标签: jquery scope settimeout


    【解决方案1】:

    你需要在each()回调中声明slide_config为一个局部变量

    var slide_config = ...;
    

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

    【讨论】:

    • @SLarks 我虽然这样做了。如果你看第二行代码 this.$slides.each(function(i){ this each 对应于每张幻灯片。然后我设置 slide_config = $.extend({... 我错过了什么吗?你可以查看完整来源websonalized.com/myplugin.js
    • @SLarks...je je je 是的,我错过了一些东西。在我设置 slide_config 之前的“var”这个词谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-05-01
    • 2012-11-26
    • 2012-05-30
    • 1970-01-01
    • 2011-07-19
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多