如何将按钮添加到表格

时间:2019-09-06 09:55:57

标签: jquery html

我有以下代码,按如下所示填充表:

    $.each(total, function () {
      var div = $('<div></div>');
      var tabel = $('<table style="width:98%"></table>');
      var body = $('<tbody></tbody>');
     $.each($(this).children('div'), function (i) {
     body.append($('<tr><td style="width:100%">' + $(this).html() + '</td></tr>'));
  });
    tabel.append(body);
    div.append(tabel);
    divs.push(div);
    });

这为我提供了以下html结构

<table style="width:98%">
<tbody>
<tr>
<td style="width:100%">Total: <span class="total">R 0.00</span></td>
</tr>
<tr>
<td style="width:100%"><span> BLAH BLAH BLAH</span></td>
</tr>
</tbody>
</table>

我想在总数之后添加一个按钮到表中,但是我无法正确获得位置。如果我执行以下操作,则它显然首先添加了按钮。如何在“总计” tr之后添加按钮? / p>

    body.prepend($('<tr><td>' + '<button type="button" class="Now disabled">Now</button>' + ' <td></tr>'));
   $.each($(this).children('div'), function (i) {
    body.append($('<tr><td style="width:100%">' + $(this).html() + '</td></tr>'));
                                });

这是我的目标

<table style="width:98%">
    <tbody>
    <tr>
    <td style="width:100%">Total: <span class="total">R 0.00</span></td>
    </tr>
    <tr>
    <td><button type="button" class="Now disabled">Now</button></td> //i want it to come in here
    </tr>
    <tr>
    <td style="width:100%"><span> BLAH BLAH BLAH</span></td>
    </tr>
    </tbody>
    </table>

3 个答案:

答案 0 :(得分:1)

首先需要选择类别为total的span元素,然后选择其tr父元素,然后在其后插入按钮代码。 只需用下面几行更改代码-

$.each($(this).children('div'), function (i) {
    body.append($('<tr><td style="width:100%">' + $(this).html() + '</td></tr>'));
});
body.find('span.total').closest('tr').after('<tr><td><button type="button" class="Now disabled">Now</button><td></tr>');

答案 1 :(得分:0)

是否不能在内部$ .each中添加if语句,以检查“ i”是否等于0,如果是,请在添加第一行之后添加按钮。

    $.each(total, function () {
      var div = $('<div></div>');
      var tabel = $('<table style="width:98%"></table>');
      var body = $('<tbody></tbody>');
     $.each($(this).children('div'), function (i) {
         body.append($('<tr><td style="width:100%">' + $(this).html() + '</td></tr>'));
         if (i === 0) {
            body.append($('<tr><td style="width:100%"><button>BUTTON STUFF HERE</button></td></tr>'));
         }
  });
    tabel.append(body);
    div.append(tabel);
    divs.push(div);
    });

答案 2 :(得分:0)

 $.each(total, function () {
          var div = $('<div></div>');
          var tabel = $('<table style="width:98%"></table>');
          var body = $('<tbody></tbody>');
         $.each($(this).children('div'), function (i) {
         body.append($('<tr><td style="width:100%">' + $(this).html() + '</td> 
         </tr><tr><td><button type="button" class="Now disabled">Now</button> 
   </td></tr>'));
      });
        tabel.append(body);
        div.append(tabel);
        divs.push(div);
        });
相关问题