文字('')后保持相同的高度和宽度

时间:2014-05-25 14:36:19

标签: javascript jquery html

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>

1 个答案:

答案 0 :(得分:3)

在删除文字内容之前,请指定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

参考文献: