如何使用jquery根据HTML的第一个TR中td的大小在表的第一个前面添加tr?

时间:2017-07-20 11:59:29

标签: jquery html

我想添加一个tr作为带有复选框的tbody的第一个孩子,在这里我尝试但没有得到结果。

var ss = $('tbody tr')[0]
        var trLen=$(ss).find('td').length;
        //alert(trLen);
        var cnt=0;
        $('<tr>').prepend
        for(var k=0;k<trLen;k++) {
                $('<td>').prepend
                $('<input />', {
                    type : 'checkbox',
                    id : 'col_'+cnt,
                    class : 'dt-checkboxes',
                    value : name
                }).prependTo($(this));

                $('</td>').prependTo($(this));
                cnt++;

        }
        $('</tr>').prependTo($(this));

HTML

<tbody><tr style="height:15.0pt;"><input type="checkbox" id="selectall" class="dt-checkboxes" value="">
            <td class="td_0_1">&nbsp;</td>
<td class="td_0_1">&nbsp;</td>
<td class="td_0_1">&nbsp;</td>
<td class="td_0_1">&nbsp;</td>
<td class="td_0_1">&nbsp;</td>
<td class="td_0_1">&nbsp;</td>
<td class="td_0_1">&nbsp;</td>
<td class="td_0_1" rowspan="2">Total general</td>
          </tr>
</tbody>

帮我解决问题 感谢

2 个答案:

答案 0 :(得分:2)

在这里,您将使用示例解决方案https://jsfiddle.net/8w05u9oa/1/

&#13;
&#13;
function functionName() {
    setTimeout(function(){ //Your Code }, 3000);
}
&#13;
$('table tbody').prepend('<tr></tr>');
$('table tbody tr:nth-child(2) td').each(function(){
	$('table tbody tr:nth-child(1)').append('<td><input type="checkbox" class="checkbox" /></td>');
});
&#13;
table, tr, th, td {
  border: 1px solid;
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

<强>样本

var ss = $('table tbody tr:first td');
console.log(ss.length)

//get number of td in first row of table
var pre = '<tr>';
for(var i=0;i<ss.length;i++){
 pre+= '<td><input type="checkbox" id="col_'+i+'" class="dt-checkboxes" value="name"/>&nbsp;</td>';
}
pre+='</tr>';
$('table tbody tr:first').before(pre);//add this tr before first tr of table
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border='1'>
<tbody><tr style="height:15.0pt;">
<td class="td_0_1">&nbsp;1</td>
<td class="td_0_1">&nbsp;2</td>
<td class="td_0_1">&nbsp;3</td>
<td class="td_0_1">&nbsp;4</td>
<td class="td_0_1">&nbsp;5</td>
<td class="td_0_1">&nbsp;6</td>
<td class="td_0_1">&nbsp;7</td>
<td class="td_0_1" colspan="2">Total general</td>
          </tr>
<tr style="height:15.0pt;">
<td class="td_0_1">&nbsp;1</td>
<td class="td_0_1">&nbsp;2</td>
<td class="td_0_1">&nbsp;3</td>
<td class="td_0_1">&nbsp;4</td>
<td class="td_0_1">&nbsp;5</td>
<td class="td_0_1">&nbsp;6</td>
<td class="td_0_1">&nbsp;7</td>
<td class="td_0_1" colspan="2">Total general</td>
          </tr>
</tbody></table>

你可以这样做。获取所有td并使用jQuery .each(),然后使用prepend获取td