javascript – JQuery:如果表头有一个类,则将类添加到表单元格
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – JQuery:如果表头有一个类,则将类添加到表单元格,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1962字,纯文字阅读大概需要3分钟。
内容图文
![javascript – JQuery:如果表头有一个类,则将类添加到表单元格](/upload/InfoBanner/zyjiaocheng/760/d8f1c8df603d4b77af9831ec9a239da9.jpg)
假设我有以下html:
<table>
<thead>
<tr>
<th class="alignRight">Header1</th>
<th>Header2</th>
<th class="alignLeft">Header3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row1</td> //Add class="alignRight"
<td>Row1</td>
<td>Row1</td> //Add class="alignLeft"
</tr>
<tr>
<td>Row2</td> //Add class="alignRight"
<td>Row2</td>
<td>Row2</td> //Add class="alignLeft"
</tr>
<tr>
<td>Row3</td> //Add class="alignRight"
<td>Row3</td>
<td>Row3</td> //Add class="alignLeft"
</tr>
</tbody>
</table>
如果THEAD中的TR包含类“alignRight”或“alignLeft”,我想将相同的类应用于TBODY中的相应TD.
我正在使用JQuery并尝试了以下方法,但它们似乎都没有正常工作:
$('tr').has('th.alignRight').addClass('th.alignRight');
$('tr').has('th.alignLeft').addClass('th.alignLeft');
$('thead.tr').has('th.alignRight').addClass('tbody.th.alignRight');
$('thead.tr').has('th.alignLeft').addClass('tbody.th.alignLeft');
if ($('thead.tr').has('th.alignRight')){
$('tbody.tr').addClass('th.alignRight');
}
if ($('thead.tr').has('th.alignRight')){
$('tbody.tr.td').addClass('alignRight');
}
关于什么可能出错的任何想法?
更新:
我想补充一点,我已经使用.each()循环遍历表.我只需要添加条件,如果当前表头具有该类,则将该相同的类添加到表格单元格中.在当前迭代期间添加额外的迭代听起来会导致性能问题.真的吗?
环:
function(res) {
var tbl_body = "";
$.each(res, function () {
var tbl_row = "";
$.each(this, function (k, v) {
//Irrelevant code
tbl_row += "<td>" + v + "</td>";
})
tbl_body += "<tr>" + tbl_row + "</tr>";
})
$("#print").html(tbl_body);
},
//Other irrelevant code
解决方法:
我认为你没有看到jquery选择器是如何工作的.
$(‘thead.tr’)表示:找到我所有拥有tr类的thead.显然不是你想做的.
这里应该有一个代码:
$('tbody tr td').each(function(index){
//index contains the current td index in the parent tr (1,2,3),(1,2,3)...
//if the corresponding th has a class
if($('thead tr th').eq(index).attr('class') != ''){
//put this class on the current td
$(this).addClass($('thead tr th').eq(index).attr('class'));
}
});
检查td是否有类是没有必要的,因为如果给它一个空参数,addClass什么也不做.
内容总结
以上是互联网集市为您收集整理的javascript – JQuery:如果表头有一个类,则将类添加到表单元格全部内容,希望文章能够帮你解决javascript – JQuery:如果表头有一个类,则将类添加到表单元格所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。