javascript 使用 jQuery 修改表格结构(合并单元格)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10219242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Modify table structure (merge cells) with jQuery
提问by user1342645
I have a table
我有一张桌子
<table>
<tr><td>9:00</td><td id='ts9'>task1</td></tr>
<tr><td>10:00</td><td id='ts10'></td></tr>
<tr><td>11:00</td><td id='ts11'>task2</td></tr>
<tr><td>12:00</td><td id='ts12'>task3</td></tr>
</table>
and I need to merge cells with id 10 and 11 in one because that task takes 2 hours. I am using jQuery.
我需要将 ID 为 10 和 11 的单元格合二为一,因为该任务需要 2 个小时。我正在使用 jQuery。
I thought about:
我想过:
$("#ts9").attr('colSpan', 2);
But it wont work.
但它不会工作。
回答by David says reinstate Monica
If you must use jQuery, then this works:
如果您必须使用 jQuery,那么这有效:
$('#ts10')
.text($('#ts11').text())
.attr('rowspan','2')
.closest('tbody')
.find('#ts11')
.remove();?
Or, somewhat more concisely:
或者,更简洁一些:
$('#ts10')
.text($('#ts11').remove().text())
.attr('rowspan','2');?
And a slightly more...useful approach, which will merge cells of adjacent rows with the class
of two
:
和稍微更多...有用的方法,这将合并相邻行的细胞用class
的two
:
$('tr td.two').each(
function(){
var that = $(this),
next = that.parent().next().find('.two');
if (next.length){
that
.text(next.remove().text())
.attr('rowspan','2');
}
});
回答by Manny in Cape Town
This works for me. Merges cells with same text: Logic: for each cell, if next cell same text, remove next cell, increment colSpan. (Note "colSpan", not "colspan" - apparently a browser compat issue)
这对我有用。合并具有相同文本的单元格: 逻辑:对于每个单元格,如果下一个单元格相同的文本,则删除下一个单元格,增加 colSpan。(注意“colSpan”,而不是“colspan”——显然是浏览器兼容性问题)
$('#tblData tbody tr:first-child td').each(function(){
var colSpan=1;
while( $(this).text() == $(this).next().text() ){
$(this).next().remove();
colSpan++;
}
$(this).attr('colSpan',colSpan);
});
回答by Devtrix.net
You actually need to add rowspanto ds10 and then removets11 from the second row here. Change you code from colspan to rowspan, add the following
您实际上需要将rowspan 添加到 ds10,然后从此处的第二行中删除ts11。将代码从 colspan 更改为 rowspan,添加以下内容
$("#ts11").remove();
and you should get result you need. But i didn't personally try changing rowspan/colspan attributes via jquery, i'm just assuming it works well. Hope it helps.
你应该得到你需要的结果。但我没有亲自尝试通过 jquery 更改 rowspan/colspan 属性,我只是假设它运行良好。希望能帮助到你。
p.s.: corrected numbers, thought u need to merge 9 and 10 first :)
ps:更正的数字,认为你需要先合并 9 和 10 :)