2016-07-24 4 views
0

私は、単純なjsの変数があります:私は、.chosenをクリックするとJS変数名

$(document).on('click', '.chosen', function (e) { 
    var type = $(this).data('type'); 
}); 

:私は、データの属性を取得する機能を持っている<div class="chosen" data-type ='first'>

、その後

var check_first = 0; 
var check_second = 1; 

を値が「first」のtype変数を取得します。

それから私は一番上にある2つの変数の一つを特定し、0の値を取得するには、この値を使用したい:

例えば:

var chosen = check_ + type; //of course wrong, and should give "check_first" when properly written. 
console.log(chosen); //giving 0 as the result 

どのように私はこれを達成することができますか?

答えて

4

あなたの最高のチャンスは、これを達成するために、単純なキーと値のオブジェクトを使用することです:

var check = { 
    first: 0, 
    second: 1 
}; 

$(document).on('click', '.chosen', function (e) { 
    var type = $(this).data('type'); 
    console.log(check[type]); 
}); 
+0

ありがとうございました。私はこれを試してみましょう。 –