更改附加元素的属性

时间:2019-01-08 09:29:05

标签: javascript jquery html-table row

for (var i = 0; i < 10; i++) {
  var tr = $("<tr></tr>")
  tr.append("<td>1</td>");
  tr.append("<td>2</td>");

  $("table tbody").append(tr)

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody></tbody>
</table>

如何追加行,然后动态更改第二行的行跨度。我想发生的事情是这样的:

<table border='1'>
  <tbody>
    <tr>
      <td rowspan="2">1</td>
      <td>2</td>
    </tr>
    <tr>
      <td>2</td>
    </tr>
    <tr>
      <td rowspan="2">1</td>
      <td>2</td>
    </tr>
    <tr>
      <td>2</td>
    </tr>
    <tr>
      <td rowspan="2">1</td>
      <td>2</td>
    </tr>
    <tr>
      <td>2</td>
    </tr>
    <tr>
      <td rowspan="2">1</td>
      <td>2</td>
    </tr>
    <tr>
      <td>2</td>
    </tr>
    <tr>
      <td rowspan="2">1</td>
      <td>2</td>
    </tr>
    <tr>
      <td>2</td>
    </tr>
  </tbody>
</table>
我尝试使用索引,但未添加rowspan

感谢您的帮助。

FYI:我要发生的事情是先附加,然后在附加行后更改行跨度

4 个答案:

答案 0 :(得分:0)

希望我能达到您的要求。

我根据第二个片段的结果。

for (var i = 0; i < 10; i++) {
  var tr = $("<tr></tr>")
  tr.append("<td>1</td>");
  tr.append("<td>2</td>");

  $("table tbody").append(tr)

}

$('button').click(function(){
$('table tr:odd td:first-child').remove();
 $('table tr:even td:first-child').attr('rowspan', 2);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
  <tbody></tbody>
</table>

<button>append</button>

答案 1 :(得分:0)

只需添加mod (%)

for (var i = 0; i < 10; i++) {
  var tr = $("<tr></tr>");
  if(i%2===0){
    tr.append("<td rowspan='2'>1</td>");
  }
  tr.append("<td>2</td>");
  $("table tbody").append(tr)
}
td, th {
  border: 1px solid #ddd;
  padding: 8px;
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
    <table>
        <tbody></tbody>
    </table>
</body>

</html>

答案 2 :(得分:0)

尝试使用html字符串,然后将其附加到您的元素上,并使行跨度动态化,例如:

    var html_string = '<tr>'
    for (var i = 0; i < 10; i++) {
    html_string+= '<td rowspan="'+i+'">1</td>'
    html_string += '<td>2</td>'
   }
   html_string +='</tr>'
   $("table tbody").append(html_string)

答案 3 :(得分:-1)

下面的代码可能有帮助,

for (var i = 0; i < 10; i++) {
  var tr = $("<tr></tr>");
  tr.append("<td>1</td>");
  tr.append("<td>2</td>");
  $("table tbody").append(tr)
}
$('table tr:odd td:first-child').remove();
$('table tr:even td:first-child').attr('rowspan', 2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border='1'>
  <tbody></tbody>
</table>