jquery - 如何用 th 标签替换所有 tr 标签

标签 jquery regex html-table

我有一张这样的 table :

<thead>    
    <tr class="row-2"><tr>
    <tr class="row-3">..<tr>
    <tr class="row-4">..<tr>
    <tr class="row-5">..<tr>
    <tr class="row-6">..<tr>
    <tr class="row-7"><tr>
    <tr class="row-8">..<tr>
    <tr class="row-9">..<tr>
    <tr class="row-10">..<tr>
    <tr class="row-11">..<tr>
</thead>

如何使用 jQuery 将所有 tr 标签替换为 thead 标签内的 th 标签?

最佳答案

获取表格 html,然后replace所有出现的事件或 tr(有关详细信息,请参阅 RegExp)。您可以将 设置为具有 id 并访问它。

$('#tableId').html($('#tableId').html().replace(/tr/gi, 'th'));

这会将整个表中的所有 tr 更改为 th。

编辑 为了获得更好的性能,感谢 jAndy。

$('#mytable').find('tr').each(function() {
    var $this = $(this);
    $this.replaceWith('<th class="' + this.className + '">' + $this.text() + '</th>');
});

.find() 比 $('#mytable > tr') 更快吗?

关于jquery - 如何用 th 标签替换所有 tr 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4374595/

相关文章:

javascript - 如何检查动态生成的 radio 输入值

java - 为什么我无法检查字符串中字符的成员资格?

html - 垂直 HTML 按钮间距问题

c - flex 是否可以选择只匹配整个单词?

正则表达式提取包含特定单词的超链接

python - 如何在 django-datatable-view 中渲染表格?

html - 如何为大于 767px 的更大屏幕应用 Bootstrap 表响应类

jquery - Backbone View 事件获得正确的目标

javascript - 如何根据选择框中的选项值更改视频的 src 值

javascript - 如何自动提交所有选中check_box的表单?