2013-07-31 87 views
1

我有這個表與每個列的文本框(他們將用於過濾)。 文本框的寬度應與相應的列相同。文本框匹配表列寬度

這是據我已經收到(簡體版):http://jsfiddle.net/9uUpP/

僞代碼解釋什麼,我想用我的當前腳本做:

document ready{ 
    var index = 0; 
    for each(th){ 
     textboxNr(index).width = this.width; 
     index++; 
    } 
} 

,你可以請參閱,文本框與寬度中的列不匹配。

重要:表+內容生成並可能不時變化,所以我必須做一個動態的解決方案。列數將永遠是相同的,但它們的寬度可以改變

回答

2

第一個孩子不會是零孩子。所以索引最初應該是1。

here。它說,兒童與指數1

則不需要在寬度px,只是價值不足夠的開始。 Check here

這裏是更新工作jsFiddle

你的代碼應該是,

$(document).ready(function() { 
    var index = 1; 
    $("#table th").each(function() { 
     $('input[type="text"]:nth-child('+index+')').css('width',$(this).width()); 
     index = index+1; 
    }); 
}); 
1

沒有必要爲這一個額外的變量,你可以使用在each方法本身的index參數,沿與:eq() Selector像:

$(document).ready(function() { 
    $("#table th").each(function (index) { 
     $('input[type="text"]:eq(' + index + ')').css('width', $(this).width()); 
    }); 
}); 

我已經使用:eq()代替:nth-child(n),因爲:nth-child(n)使用基於1的索引來符合CSS規範,但each方法中的參數index0開始,而:eq()使用基於0的索引。

FIDDLE DEMO

0

我相信指標是不正確的......

$(document).ready(function() { 
    $("#table th").each(function (i, v) { 
     $('input[type="text"]:nth-child(' + (i+1) + ')').css('width', $(this).width() + 'px'); 
    }); 
}); 

jsFiddle demo!