2012-02-13 19 views
0
//this counts how many images exist 
    var img_count = $("#gallery_scroller img").length; 
    //this is a number where I want the clicks to stop working 
    var limit_count = img_count/3; 

    var click_count = 1; 

    if (limit_count > click_count){ 

    $("#down_arrow").click(function(){ 
     click_count++ 
     var css_position = -1*click_count*300; 
     $('#gallery_scroller img').css('top', css_position); 
     alert(css_position+' '+limit_count+' '+click_count); 
    }); 
    }; 

最後にアラートが表示されるので、クリックするたびに値を確認できます。 click_countがlimit_countよりも大きいにもかかわらず、そのまま続行されます。 if条件では、click_countをlimit_countより大きい実際の数値に置き換えます。Javascript if文が正しく動作しない

+0

はclick_count 'の後にセミコロンを追加します++' –

答えて

3

ifステートメントは、clickイベントハンドラのコードに含まれていません。ハンドラが添付されると、内ののコードだけが、クリックが発生したときに実行されます。

私はあなたの望ましい結果が何であるか全くわからないんだけど、これはおそらく近い:

//this counts how many images exist 
var img_count = $("#gallery_scroller img").length; 
//this is a number where I want the clicks to stop working 
var limit_count = img_count/3; 

var click_count = 1; 

$("#down_arrow").click(function(){ 
    if (limit_count > click_count){ 
     click_count++; 
     var css_position = -1*click_count*300; 
     $('#gallery_scroller img').css('top', css_position); 
     alert(css_position+' '+limit_count+' '+click_count); 
    } 
}); 

例えば、内イベントハンドラのコードをテストを置きます。


サイドノート:セミコロンの必要はifブロックの中括弧の終わりではありません、例えば:

if (...) { 
    }; 
// ^--- no semi here 

サイド注2:私はclick_count++後にセミコロンを追加しました。それがなければ、あなたは恐怖に頼っています。それはautomatic semicolon insertionです。それ以降は改行があったので大丈夫でしたが、一般的に、セミコロンがどこにあるかの規則を学び、必要な場所に常に含めてください。

0

あなたの状態は、イベントハンドラ内である必要があります:

var click_count = 1; 

$("#down_arrow").click(function(){ 
    if (click_count < limit_count){ 
    click_count++; 
    var css_position = -1*click_count*300; 
    $('#gallery_scroller img').css('top', css_position); 
    alert(css_position+' '+limit_count+' '+click_count); 
    }; 
}); 
0
$("#down_arrow").click(function(){ 
if (limit_count > click_count){ 
    click_count++ 
    var css_position = -1*click_count*300; 
    $('#gallery_scroller img').css('top', css_position); 
    alert(css_position+' '+limit_count+' '+click_count); 
    }; 
}); 
関連する問題