[英]Global variable in JQuery is not updating it's value form inside the click function
[英]How to prevent changing variable's value inside click and fadeOut function?
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
值將增加單擊次數,直到其完全消失。 我知道應該這樣減少它,因為它位於click事件中。
但是,我只想在fadeOut中增加一次該值。 因此,單擊多次不會更改我的功能。 在這里可以做什么?
您可以設置一個標志來表示它正在執行淡入淡出。
$(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);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.