javascript - 对 jQuery 的 .each() 的基本误解(附示例)

标签 javascript jquery html css each

问题描述(Fiddle):

单击红色框会将它们变成小猫(并提醒您 i 的当前值)。单击淡入的大猫将重置所有内容。

我完全不明白为什么 alert(i) 在第一次之后的每个后续传递中都会多次触发(似乎呈指数级增长)。同样,我不明白如何防止它发生。我最初的 react 是它正在创建新的 DOM 元素,但当我只是更改 img 源时,我看不出如何。

此外,如果我的代码很糟糕,请随时指出缺陷/清理它。我总是喜欢学习更优雅的方法。

代码:

cats = [
    "http://placekitten.com/g/121/121",
    "http://placekitten.com/g/122/122",
    "http://placekitten.com/g/123/123",
    "http://placekitten.com/g/124/124",
    "http://placekitten.com/g/125/125",
    "http://placekitten.com/g/126/126",
    "http://placekitten.com/g/127/127",
    "http://placekitten.com/g/128/128",
    "http://placekitten.com/g/129/129",
    "http://placekitten.com/g/130/130"
];
count = 0;

function getRandomCats() {
    var kitties = [];
    for(i = 0; i < 3; i++) {
        rand = Math.floor(Math.random() * (9 - 0 + 1)) + 0;
        kitties[i] = cats[rand];
    }
    meow(kitties);
}

function meow(kitties) {
    $('.cats').each(function(i) {
        $(this).mousedown(function() {
            alert(i); //debug
            $('div.front img', this).attr('src', kitties[i]);
            $(this).css({
                'transform': 'rotateY(180deg)',
                '-webkit-transform': 'rotateY(180deg)',
                'transition': 'transform 500ms ease-in-out',
                '-webkit-transition': '-webkit-transform 500ms ease-in-out'
            });
            this.flipped = 1, this.locked;
            if (this.flipped && !this.locked) {
                this.locked = 1;
                count++;
                if (count > 2) {
                    $('#newCat').fadeIn();
                }
            }
        })
    });
}

var clicked = 0;
$('#newCat').mousedown(function() {
    if (clicked == 0) {
        clicked = 1;
        $(this).stop(true).fadeOut();
        $('.cats').fadeOut(1000, function() {
            this.flipped = 0, this.locked = 0, count = 0;
            $(this).hide().css({
                'transform': 'rotateY(0deg)',
                '-webkit-transform': 'rotateY(0deg)'
            });
            getRandomCats();
            $(this).fadeIn();
        });
    }
    setTimeout(function(){clicked = 0;}, 1000);
});

getRandomCats();

最佳答案

mousedown 语句不会覆盖之前绑定(bind)的函数。你可以很容易地通过把这个问题解决

$(this).unbind("mousedown");

$(this).mousedown 绑定(bind)语句之前。

附言既然你问过优雅:我建议你把你的代码分成更多的功能。如果缩进超过 2 级,代码将变得更难阅读。有时您会缩进 5 层或更多层。

关于javascript - 对 jQuery 的 .each() 的基本误解(附示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22126488/

相关文章:

javascript - 为什么我的方法没有返回对象

用于处理路径/URI 的 JavaScript 或查询库

javascript - 如果从 js 代码设置值,则 maxlength 不起作用

javascript - 当加载了 javascript 和 css 的页面时,div 垂直打开

javascript - 如何将一种日期格式转换为另一种日期格式

javascript - 内容替换函数: replacing a space with an underscore

javascript - javascript 拼接问题

javascript - 如何围绕鼠标光标创建形状?

jquery - Internet Explorer : Bad visualization of CSS Table (table-row, 表格单元格)

javascript - 您可以使用 CSS 或 JavaScript 创建逐渐变为不透明的渐变吗?