【问题标题】:How to update last column of a table with dictionary object?如何用字典对象更新表的最后一列?
【发布时间】:2017-06-18 08:29:00
【问题描述】:

我有一张表,其中每一行的最后一列需要用动态生成的字典键值对替换。下面是我的表结构,

<table id="example">
<tr>
    <td>Title</td>
    <td>T1</td>
</tr>
<tr>
    <td>Description</td>
    <td>D1</td>
</tr>
</table>

我想在每一行的末尾添加另一列。就这样,

<table id="example">
<tbody>
<tr>
    <td>Title</td>
    <td>T1</td>
    <td>T2</td>
</tr>
<tr>
    <td>Description</td>
    <td>D1</td>
    <td>D2</td>
</tr>
</tbody>
</table>

我有这个意见

var dict = { “t1”:“T2”, “t2”:“D2” } 我将如何使用 JQuery 来做到这一点?

【问题讨论】:

    标签: javascript jquery html html-table


    【解决方案1】:

    使用以下代码:

     // append the <td> inside each found <tr> in the table
     $("#example > tr").each(function(index){
         $(this).append("<td>" + value[index] + "</td>");
     });
    

    【讨论】:

      【解决方案2】:

      您可以使用last() 函数来获取每个tr 中的最后一个td,使用这样的jQuery 选择器:

      var dict = {
        "t1": "T2",
        "t2": "D2"
      }
      var index = 0;
      
      function start() {
        var x = $('#example tr')
        for (i = 0; i < x.length; i++) {
          row = x[i]
          var valInDic = index == 0 ? dict.t1 : dict.t2;
          index++;
          $(row).append('<td>' + valInDic + '</td>')
          if (index == 2)
            index = 0;
        }
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <table id="example">
        <tbody>
          <tr>
            <td>Title</td>
            <td>T1</td>
          </tr>
          <tr>
            <td>Description</td>
            <td>D1</td>
          </tr>
      
        </tbody>
      </table>
      <button onclick=start() ">Start</button>

      我希望这会有所帮助;)

      【讨论】:

        【解决方案3】:

        可以使用以下代码实现,

        var dict = {
                    "t1": "T2",
                    "t2": "D2"
                    }
        var count = 0;
        $.each (dict, function (field, value) {
            $('#example tr').each(function() {
                if($("tr").index(this) == count){
                      $(this).find('td:last').after('<td>' + value + '</td>');
                  }
              });
            count++;
        });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
        <table id="example">
            <tr>
                <td>Title</td>
                <td>T1</td>
            </tr>
            <tr>
                <td>Description</td>
                <td>D1</td>
            </tr>

        【讨论】:

          猜你喜欢
          • 2019-02-18
          • 1970-01-01
          • 2019-12-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-12
          相关资源
          最近更新 更多