javascript - 如何防止在 click 和 fadeOut 函数中更改变量的值?

标签 javascript jquery

HTML

<div class="dropdown">
    <label class="add-genre-filter not-selected">Add genre filter</label>
    <select class="filter" name="filter[]">
        <option value="some-value">Some Item</option>
        <option value="some-value">Some Item</option>
        <option value="some-value">Some Item</option>
        <option value="some-value">Some Item</option>
    </select>
    <span class="cancel"> x </span>
</div>

JS

$(document).ready(function(){
    var genreLimit = 3;

    $('.dropdown .add-genre-filter').live( 'click', function(){
        genreLimit ? ( $(this).parent().append(options) , genreLimit-- ) : false;
        console.log(genreLimit);
    });
    $('.dropdown .cancel').live( 'click', function(){
        $(this).prev().fadeOut("normal", function(){ $(this).remove(); });
        $(this).fadeOut("normal", function(){ genreLimit++; $(this).remove(); });
        console.log(genreLimit);
    });

});

注意:我正在使用 jQuery 1.6,这就是为什么仍然使用 live()功能

点击 <span class="cancel">两者selectspan淡出并从文档中删除。同时它增加了genreLimit的值。 作者 1

但是如果我反复点击span中的x然后genreLimit 值随着点击次数的增加而增加,直到完全淡出。我知道它应该像这样减少,因为它位于点击事件内部。

但是,我只想在淡出时增加该值一次。因此,多次点击不会改变我的功能。这里可以做什么?

最佳答案

您可以设置一个标志来表示它正在执行淡入淡出..

$(document).ready(function(){
    var genreLimit = 3;
    var is_fading = false;

    $('.dropdown .add-genre-filter').live( 'click', function(){
        genreLimit ? ( $(this).parent().append(options) , genreLimit-- ) : false;
        console.log(genreLimit);
    });
    $('.dropdown .cancel').live( 'click', function(){
        if (is_fading) return; // don't run if it is already fading...

        is_fading = true;
        // choose the correct callback to 'unlock' the flag..
        $(this).prev().fadeOut("normal", function(){ $(this).remove(); is_fading = false;? });
        $(this).fadeOut("normal", function(){ genreLimit++; $(this).remove(); is_fading = false;? });
        console.log(genreLimit);
    });
});

关于javascript - 如何防止在 click 和 fadeOut 函数中更改变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27910287/

相关文章:

javascript - HTTP 错误 : 400, hosting.rewrites[0] 不完全是 [subschema 0 ],[subschema 1]

javascript - 如何从一个 svg 中的路径元素链接到另一个 svg 的不同元素

c# - 使用 javascript 中的参数调用 ASP.net 函数

javascript - JQuery 电子邮件验证不起作用

javascript - 无法加载 m3u8 : no EXTm3u delimiter JWPlayer Error

javascript - 如何用javascript实现音乐的平滑过渡

javascript - 你如何检查 jquery .html() 变量和 ruby​​ on rails 生成的 html 之间的相等性?

javascript - for 循环增量,小数点停止在 1.42,而不是继续直到计算完成

javascript - clearInterval 不会破坏 setInterval 计时器

javascript - Asp.NET 未获取 javascript 设置的自定义属性的更新值