动态表列按id更新,完成了吗?

时间:2012-07-14 19:17:23

标签: javascript jquery html ajax json

我是Ajax / Json的新手,所以我想知道以下内容是否至少接近最佳实践。目标是每隔x秒更新一个表的特定列(在本例中为数量和价格)。

我有一个像这样定义的HTML表:

<table id="#edition_table>
    <tbody>
    <tr>
        <td class="name"><a href="?card=12345">Lightning Bolt</a></td>
        [...]
        <td class="qty">2</td>
        <td class="price">$4.99</td>
    <tr>
    <tr>
        <td class="name"><a href="?card=23456">Fireball</a></td>
        [...]
        <td class="qty">0</td>
        <td class="price">$0.07</td>
    <tr>
    [...]
    </tbody>
</table>

一个JS函数定义如下:

function edition_update(edition)
{
    var table_rows = $('#edition_table').find('tbody tr td.name a');

    $.ajax({
    type: 'GET', url: 'ajax_edition_update.php', data: { edition : edition }, dataType: 'json',
    success: function(json_rows)
    {
          var new_qty, new_price;

          table_rows.each(function(index) {
                var td_id = $(this).attr('href').replace('?card=', '');

                for (i in json_rows) {
                    if (json_rows[i].card_id == td_id)
                    {
                        new_qty = json_rows[i].qty;
                        new_price = json_rows[i].low_price;
                        break;
                    }
                }

                var parent_tr = $(this).parent().parent();

                parent_tr.find('td.qty').text(new_qty);
                parent_tr.find('td.price').text(!isNaN(new_price) ? '$' + new_price : new_price);
          });
    }
    });

    setTimeout(edition_update, 30000, edition);
}

PHP文件返回一个包含card_id,qty和low_price的JSON。

这确实很好用。我想我可以在class = name td上设置一个data-id=[card_id]来摆脱.replace,但是由于id已经存在,这有点会破坏html的足迹。

真正的问题是,是否有可能或必要的性能改进(特别是关于两个循环)?当然,每个表的目标行数为500,内容和顺序完全是动态/不可预测的。

0 个答案:

没有答案