【问题标题】:Textboxes matching table column width匹配表格列宽的文本框
【发布时间】:2013-07-31 13:34:26
【问题描述】:
我有这个表,每列都有一个文本框(它们将用于过滤)。
文本框应与相应列的宽度相同。
据我所知(简化版):http://jsfiddle.net/9uUpP/
伪代码解释了我想用我当前的脚本做什么:
document ready{
var index = 0;
for each(th){
textboxNr(index).width = this.width;
index++;
}
}
如您所见,文本框的宽度与列不匹配。
重要:表格+内容是生成的,可能会不时发生变化,所以我必须做一个动态的解决方案。列数将始终相同,但它们的宽度可能会改变
【问题讨论】:
标签:
javascript
jquery
html-table
dynamic-sizing
【解决方案1】:
第一个孩子不会是第 0 个孩子。所以 index 最初应该是 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;
});
});
【解决方案2】:
为此不需要额外的变量,您可以在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 方法中的index 参数从0 和@987654333 开始@ 使用从 0 开始的索引。
FIDDLE DEMO
【解决方案3】:
我认为索引不正确...
$(document).ready(function () {
$("#table th").each(function (i, v) {
$('input[type="text"]:nth-child(' + (i+1) + ')').css('width', $(this).width() + 'px');
});
});
jsFiddle demo!