2016-04-13 43 views
1

所以我一直試圖讓這個小小的代碼工作。但是,我不確定這是我的語法,還是我錯誤地做了這個。此代碼的目標是讓用戶輸入一個字符串,如"H2" or "Li",並返回div中「與測試」字符串關聯的數字。當我運行代碼時,它不會返回任何內容。jQuery中的「Key」對象無法正常工作

<form> 
      <input type="text" name="atomNameOne"/> 
</form> 
     <button name="moleRatios">Submit!</button> 
     <br/> 
     <br/> 
     <br/> 
    <div id="testing"></div> 

這是與我的代碼相關的jQuery代碼。

$('button[name=moleRatios]').click(function(){ 
    var compound = { 
    H2 = 2.01594, 
    Li = 6.939, 
    Be = 9.0122, 
    B = 10.811 
    } 

    var search = function(name) { 
     for(var key in compound) { 
      if(compound[key] === name) { 
      return compound[key]; 
      } 
     } 
    }; 


    var $atomValueOne = search($('input[name=atomNameOne]').val()); 


    $('#testing').text($atomValueOne); 

    }); 
+2

它看起來像這樣'VAR複合= { H2:2.01594, 李:6.939, 要:9.0122, B:10.811, }' – uzaif

+0

你也並不需要一個'for'環搜索通過「複合」對象。 –

+0

爲什麼?我以爲這就是你通過「字典」功能看待的方式 – mobimobi

回答

0

有一種錯誤的語法有下式給出:

var compound = { 
H2 = 2.01594, 
Li = 6.939, 
Be = 9.0122, 
B = 10.811 
} 

應該

var compound = { 
H2: 2.01594, 
Li: 6.939, 
Be: 9.0122, 
B: 10.811 
} 

然後

化合物[關鍵]將返回2.01594如果key爲H2,也許你想

if(compound[key] === name) 

if(key == name) 

而不是 其餘的肩膀d是定義一個對象相同

+0

非常感謝,一直都是這個問題! – mobimobi

0

更換

if(compound[key] === name) 

if(key === name) 

,並糾正對象語法在其他的答案

0

正確的方法是

var compound = { H2: 2.01594, Li : 6.939, Be: 9.0122, B : 10.811 } 

propertyName的:的PropertyValue格式。
要訪問propertyName的一個字符串,使用 -

var search = function(name) { 
    for(var key in compound) { 
     if(key === name) { 
     return compound[key]; 
     } 
    } 
}; 

其中迭代「鑰匙」將總是給出的名稱(字符串)的屬性和格式對象名[迭代]將總是給該財產的價值。