Fiddle Example

Updated Example

有人可以告诉我删除内容后如何使表格保持相同的高度和宽度。我想确保在使用td清除内容后,表中的每个thtrtext()都没有变化。我要这样做的原因是因为表固定标头脚本从AJAX注入数据后存在一些滚动问题。我需要查看text();之后高度和宽度的变化是否是问题的原因。

我的尝试会在每次点击时缩小一点桌子。

$('#cleartable').on('click', function () {

    var clear = $(".toptable td,.toptable th");
    var tableheight,tablewidth;
    clear.each(function(){
    tableheight = $(this).height(),tablewidth = $(this).width();

    });
    clear.filter(function () {
        return $(this).index() !== 0;
    }).text('');
    clear.css("width",tablewidth).css("height",tableheight);

});


HTML:

<button id="cleartable">Change</button>
<table class="toptable">
    <tr>
        <th class="image">-</th>
        <th class="image">-</th>
        <th class="image">-</th>
    </tr>
    <tr>
        <td class="description">Name</td>
        <td class="description">Alan</td>
        <td class="description">John</td>
    </tr>
    <tr>
        <td class="title">Age</td>
        <td class="title">8</td>
        <td class="title">9</td>
    </tr>
</table>

最佳答案

在删除文本内容之前,请指定height元素的width / <td>(在这种情况下,请使用.css()方法):

$('#cleartable').on('click', function () {
    // selecting the td:first-child elements
    $('table.toptable td:first-child')
    // moving to select the siblings:
    .siblings()
    // adjusting the css:
    .css({
        // i: the index of the current element over which we're iterating,
        // h: the current value of the property we're manipulating (before adjustment),
        // these names are arbitrary, and can be anything (I use these variable-names
        // simply as a matter of personal taste, to represent the property I'm working
        // with):
        'height' : function(i,h){
            return h
        },
        'width' : function(i,w){
            return w
        }
    }).text('');
});


JS Fiddle demo

参考文献:


css()
siblings()

10-08 17:10