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">
两者select
和span
淡出并从文档中删除。同时它增加了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/