[英]Textboxes matching table column width
I have this table with a textbox for each column (they are going to be used for filtering). 我有这个表,每个列都有一个文本框(它们将用于过滤)。 The textboxes should be the same width as the corresponding column.
文本框的宽度应与相应列的宽度相同。
This is as far as I've gotten (simplified version): http://jsfiddle.net/9uUpP/ 这是我得到的(简化版): http : //jsfiddle.net/9uUpP/
Pseudo-code explaining what I am trying to do with my current script: 伪代码解释了我正在尝试使用当前脚本执行的操作:
document ready{
var index = 0;
for each(th){
textboxNr(index).width = this.width;
index++;
}
}
As you can see, the textboxes doesn't match the columns in width. 如您所见,文本框与宽度中的列不匹配。
important: The table + content is generated and may change from time to time, so I have to make a dynamic solution. 重要:表+内容是生成的,可能会不时变化,因此我必须制作动态解决方案。 The number of columns will always be the same, but their width may change
列数始终相同,但其宽度可能会更改
First child will not be 0th child. 第一个孩子不会是第0个孩子。 So index should be 1 initially.
所以索引最初应为1。
Look here . 看这里 It says children index starts with 1.
它说儿童指数从1开始。
Then px
is not needed in width, just the value does enough. 然后宽度不需要
px
,只需要足够的值。 Check here 点击这里
Here is the updated working jsFiddle 这是更新的工作jsFiddle
Your code should be, 你的代码应该是,
$(document).ready(function () {
var index = 1;
$("#table th").each(function () {
$('input[type="text"]:nth-child('+index+')').css('width',$(this).width());
index = index+1;
});
});
There's no need of an extra variable for this, you can use the index
parameter in the each
method itself, along with the :eq() Selector
like: 这不需要额外的变量,你可以在
each
方法本身使用index
参数,以及:eq() Selector
如:
$(document).ready(function () {
$("#table th").each(function (index) {
$('input[type="text"]:eq(' + index + ')').css('width', $(this).width());
});
});
I have used :eq()
here instead of :nth-child(n)
since :nth-child(n)
uses 1-based indexing to conform to the CSS specification but the index
parameter in the each
method starts from 0
and :eq()
use 0-based indexing. 我使用了
:eq()
而不是:nth-child(n)
因为:nth-child(n)
使用基于1的索引来符合CSS规范,但each
方法中的index
参数从0
开始:eq()
使用基于0的索引。
I believe the indexes were incorrect... 我认为索引不正确......
$(document).ready(function () {
$("#table th").each(function (i, v) {
$('input[type="text"]:nth-child(' + (i+1) + ')').css('width', $(this).width() + 'px');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.