0

我正在使用MetroJs,并且我使用了一个单独的函数来初始化每个图块,因为我一次只想看到一个图块的背面。因此,使用此代码,每个图块都完全动画化,显示背面和正面,然后暂停一段时间,以便其他图块执行相同操作。

无论如何,这并不重要,因为您可以看到我的代码现在非常低效,有很多重复代码。你认为我可以如何改进它以使其更短?我考虑过使用循环来初始化它们,但我不知道该怎么做。

我使用单独的初始化程序的原因是我需要创建一个适用于每个图块的计数,但我无法从内部创建计数变量.liveTile()

JS:

var count1 = 0;
var count2 = 0;

$('.live-tile.one').liveTile({
    animationComplete:function() {
        count1++;
        if (count1 == 2) {
            $('.live-tile.one').liveTile("restart", 10000);
            count1 = 0;
        }
    }
});

$('.live-tile.two').liveTile({
    animationComplete:function() {
        count2++;
        if (count2 == 2) {
            $('.live-tile.two').liveTile("restart", 10000);
            count2 = 0;
        }
    }
});

使count变量更清晰的一种方法是将每个初始化移动到一个函数中,该函数在该函数内创建 count 变量,但我需要再次使其余部分更有效。

4

1 回答 1

0

你可以添加data-count='0'.live-tile项目?

$('.live-tile').liveTile({
    animationComplete:function() {
        var count = parseInt($(this).data('count'));
        count++;
        $(this).data('count', count);
        if (count == 2) {
            $(this).liveTile("restart", 10000);
            $(this).data('count', '0');
        }
    }
});

如果没有,您也可以这样做:

var counts =[0, 0, 0, 0, 0;]

$('.live-tile').liveTile({//.find will let you access all divs (.one, .two, etc.) at once that .live-tile contains
    animationComplete:function() {
        var index = $(this).index();//the index of div item (among the div items of .live-tile, it will be 0 for .one, 1 for .two, 2 for .three, etc.
        var count = counts[index];//bring the current value based on the index
        count++;//increase it 
        counts[index] = count;//restore it to the correct index
        if (count == 2) {
            $(this).liveTile("restart", 10000);
            counts[index] = 0);//reset
        }
    }
});
于 2015-05-05T03:23:37.610 回答