我渲染动态附加 tr
、td
和带有类名的输入标记,并且我还编写了单独的 css
样式,但它未应用动态 tr
。
请找到我的代码片段。
<table style="width:100%" class="tSheet">
<tr class="t-header">
<th class="t-head">sno</th>
<th class="t-head">Description</th>
<th class="t-head">Debit</th>
<th class="t-head">Credit</th>
</tr>
<tr>
<td class="t-content"><input type="text" class="t-input" /></td>
<td class="t-content"><input type="text" class="t-input" /></td>
<td class="t-content"><input type="text" class="t-input" /></td>
<td class="t-content"><input type="text" class="t-input" /></td>
</tr>
</table>
CSS 样式:
.tSheet .t-head,.t-content {
border: 1px solid black;
}
.t-input{
border:0px none;
}
.t-input:focus{
outline:0;
}
我的 JavaScript 函数:
$(function () {
$('input').css("width", $('input').parent().width());
for(var i=0;i<3;i++)
{
$("<tr><td class='t-content'><input class='t-content t-input/>'</td><td class='t-content'><input class='t-input/>'</td><td class='t-content'><input class='t-input/>'</td><td class='t-content'><input class='t-input/>'</td></tr>").attr({ class: "a" }).appendTo('.tSheet')
}
})
最佳答案
这是因为class
属性关闭放错了位置
- 而不是使用
attr()
使用addClass()
用于添加类 - 对于应用宽度,请使用
css()
使用回调,也可以在添加动态元素后执行,或者您可以设置 csswidth:100%
输入元素 - 在你的代码中类名属性没有正确关闭,修改
<input class='t-content t-input/>'
至<input class='t-content t-input'/>
和<input class='t-input/>'
至<input class='t-input'/>
for (var i = 0; i < 3; i++) {
$("<tr><td class='t-content'><input class='t-content t-input'/></td><td class='t-content'><input class='t-input'/></td><td class='t-content'><input class='t-input'/></td><td class='t-content'><input class='t-input'/></td></tr>").addClass("a").appendTo('.tSheet')
}
$('input').css("width", function() {
return $(this).parent().width()
});
.tSheet .t-head,
.t-content {
border: 1px solid black;
}
.t-input {
border: 0px none;
}
.t-input:focus {
outline: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="width:100%" class="tSheet">
<tr class="t-header">
<th class="t-head">sno</th>
<th class="t-head">Description</th>
<th class="t-head">Debit</th>
<th class="t-head">Credit</th>
</tr>
<tr>
<td class="t-content">
<input type="text" class="t-input" />
</td>
<td class="t-content">
<input type="text" class="t-input" />
</td>
<td class="t-content">
<input type="text" class="t-input" />
</td>
<td class="t-content">
<input type="text" class="t-input" />
</td>
</tr>
</table>
关于javascript - 如何将 css 样式应用于带有 td 和 input 标签的动态 tr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32557812/