jquery - 如何替换表列值

时间:2012-06-01 15:53:07

标签: jquery jquery-ui

我是一个jQuery新手。我有下表 -

<table summary="This table lists all values in storage."> 
         <caption>Values in storage</caption>
         <tbody> 
         <tr> 
           <th scope="row">JetBlue 983</th> 
           <td>Boston (BOS)</td> 
           <td>New York (JFK)</td> 
         </tr> 
         <tr> 
           <th scope="row">JetBlue 354</th> 
           <td>San Francisco (SFO)</td> 
           <td>Los Angeles (LAX)</td> 
         </tr> 
       <tr> 
           <th scope="row">JetBlue 465</th> 
           <td>New York (JFK)</td> 
           <td>Portland (PDX)</td> 
         </tr> 
         </tbody> 
       </table> 

现在,我想读取本地存储并在每次加载页面部分时使用jquery填充第二列中的值。最简单的方法是什么?

1 个答案:

答案 0 :(得分:3)

您可以使用以下方式执行此操作

我假设您将json编码数据保存到LocalStorage

$(function{
  var data  = JSON.parse(localStorage.getItem('ITEM_KEY'));
  // data is an object now
  // find 2nd columns and populate
  $('tr td:nth-child(2)').each(function(i){

    $(this).text(data[i]);
   });
})

假设您要插入从localStorage找到的相同数据。并且数据数组中的元素数量与列数相同。

参考:$.each:nth-child selector