在tbody上使用empty()可以不断调整整个表的宽度

时间:2014-08-15 18:19:13

标签: javascript jquery html css

我正在使用jQuery在tbody内重新加载数据。但是,标题列宽度保持调整大小事件,虽然我为列添加固定宽度。我正在使用Firefox。

简单的HTML表格:

<table style="width:95%;" border="1" align="center" >
    <thead>
        <tr>
        <td class="header" style="width:20%">ProductFamily
            <select onchange="selectCategoryChange()">
                <option "1">1</option>
                <option "2">2</option>
            </select>
        </td>
        <td class="header" style="width:20%">ProductNum</td>
        <td class="header" style="width:30%">ProductDesc</td>
        <td class="header" style="width:5%">DT Rate</td>
        <td class="header" style="width:5%">List Rate</td>
        <td class="header" style="width:5%">Man Hour Unit</td>
        <td class="header" style="width:5%">Precall</td>
        <td class="header" style="width:5%">SOW</td>
        <td class="header" style="width:5%">Box</td>
         </tr>
    </thead>
    <tbody  id="tbodyDataRow">
        <!-- Data Rows Here -->
    </tbody>
</table>

当tbody.empty()时,它会自动调整标题列的宽度,这会使页面看起来很难看。然后当我重新加载新行时,它将其重新调整为原始宽度。这是我的Jquery代码。

$(document).ready(function() {
    selectCategoryChange = function()
    {
        var tbody = $("#tbodyDataRow");
        tbody.empty();

    };
});

3 个答案:

答案 0 :(得分:1)

这有效,但我没有在所有浏览器中测试它。将HTML更改为:

<table border="1" align="center">
    <thead>
        <tr>
            <th>ProductNum</th>
            <th>Product</th>
            <th>DT Rate</th>
            <th>List Rate</th>
            <th>Man Hour Unit</th>
            <th>Precall</th>
            <th>SOW</th>
            <th></th>
        </tr>
    </thead>
    <tbody id="tbodyDataRow">
        <!-- tbody Content -->
    </tbody>
</table>

无论如何,你应该避免使用内联样式。添加此CSS文件:

table {
    border: 1px solid black;
}
.header {
    background-color: #ccc;
    font-weight: bold;
    min-width: 200px;
}

这将解决您的问题,但同样不是跨浏览器测试。您可以考虑允许调整大小。

Final result Fiddle

答案 1 :(得分:0)

你的表style="width:95%;"就是问题所在。您期望宽度为8 X 200px = 1600px的表格,但您的表格宽度应为95%,可以大于或等于1600px。如果它是不同的,标题将自动调整。我很抱歉我的英语。

答案 2 :(得分:0)

我在ul元素上应用了empty()函数时遇到了类似的问题。 HTML结构:

<table>
  <tr>
    <td>
        <ul id="list"></ul>
    </td>
    <td>
     ...
    </td> 
  </tr>

我有一个JS计时器,它调用一个负责刷新列表内容的ajax函数(ul)。要更新列表(ul),我开始使用以下代码清空它:

$("#list").empty();

在每次迭代时,即使内容相同,列宽也会增加。我最后通过使用replaceWith函数用初始内容替换了内容,这次没关系:

$("#list").replaceWith('<ul id="list"></ul>');