2017-06-02 58 views
0

我在每個表格單元格上都有id。每個id在Javascript對象中都有匹配的關鍵字。 Ajax調用將返回帶有值的對象。如果密鑰匹配單元格ID,我想循環訪問表格併爲每個表格單元格賦值。下面是例子:匹配表ID與對象鍵?

HTML表:

<table class="tblData"> 
    <tr> 
     <th>Last Name</th> 
     <td id="st_lname"></td> 
    </tr> 
    <tr> 
     <th>First Name</th> 
     <td id="st_fname"></td> 
    </tr> 
    <tr> 
     <th>DOB</th> 
     <td id="st_dob"></td> 
    </tr> 
</table> 

的Javascript:

$.ajax({ 
    type: 'POST', 
    url: 'Components/getRecords.cfc?method='+getMethod, 
    data: {'userID':userID}, 
    dataType: 'json' 
}).done(function(obj){ 
    if(obj.STATUS == 200){ 
     //Here I can access my obj.DATA values and get the key for each value 
     $('.tblData table tr td').each(function(){ 
      $(this).attr('id').toUpperCase(); 
     }); 

     return true; 
    }else{ 
     return false; 
    } 
}).fail(function(jqXHR, textStatus, errorThrown){ 
    alert(errorThrown); 
}); 

這裏是我的物體的外觀我收到來自服務器的響應後:

{"STATUS":200,"DATA":{"ST_DOB":"03/16/2010","ST_FNAME":"John","ST_LNAME":"Miller"}} 

我後獲得成功的返回結果我想像上面提到的那樣遍歷表並在每個tabl的對象中查找匹配鍵e cell id並將值分配給該單元格。如果有人能幫助請讓我知道。謝謝。

+1

這是一個錯誤賦值?或者你想讓別人爲你寫解決方案? –

+0

我試圖找到使用對象鍵找到匹配id的最佳方法。我不需要有人寫解決方案。謝謝。 –

回答

2

您的選擇器不正確。它應該是.tblData tr td。您可以使用jQuery的text()方法

var res = { 
 
    "STATUS": 200, 
 
    "DATA": { 
 
    "ST_DOB": "03/16/2010", 
 
    "ST_FNAME": "John", 
 
    "ST_LNAME": "Miller" 
 
    } 
 
}; 
 

 
$('.tblData tr td').each(function(i, ele) { 
 
    var id = $(ele).attr('id').toUpperCase(); 
 
    var value = res.DATA[id]; 
 
    if (value) { 
 
    $(ele).text(value); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table class="tblData"> 
 
    <tr> 
 
    <th>Last Name</th> 
 
    <td id="st_lname"></td> 
 
    </tr> 
 
    <tr> 
 
    <th>First Name</th> 
 
    <td id="st_fname"></td> 
 
    </tr> 
 
    <tr> 
 
    <th>DOB</th> 
 
    <td id="st_dob"></td> 
 
    </tr> 
 
</table>