我有以下HTML:
<table id="ChatTable" class="ChatBox" style="margin-left:0px !important">
<tr class="row1">
<td></td>
</tr>
<tr class="row2">
<td></td>
</tr>
</table>
以及以下jQuery:
<script>
$(document).ready(function () {
var Tabletr= $(".ChatBox > tbody > tr:odd");
});
</script>
如何在Jquery中获取Odd行的类名?
答案 0 :(得分:2)
简单地
var $elems = $("table.ChatBox tr:odd");
应该有用。
要获得他们的课程(请参阅下面的Juicy Scripter),
$elems.each(function(){ console.log(this.className); //do whatever with the class names. });
答案 1 :(得分:1)
attr
方法或JavaScript中的元素的className
属性之外,jQuery本身不提供直接检索DOM元素类的方法:
$(document).ready(function () {
var Tabletr= $(".ChatBox > tbody > tr:odd");
var firstElementClass = Tabletr.eq(0).attr('class');
// Previous is the same as
var firstElementClass = Tabletr.get(0).className;
// Due to fact that Tabletr may contain more that one row you may want to iterate and collect classes names.
var classes = [];
Tabletr.each(function(){
classes.push(this.className);
// OR
classes.push($(this).attr('class'));
});
});
答案 2 :(得分:1)
试试这个:
<script>
$(document).ready(function () {
var Tabletr= $(".ChatBox").children("td:odd").attr("class");
alert (Tabletr);
}
});
</script>
你也可以使用:first而不是:odd如果你想获得第一个td类。
答案 3 :(得分:0)
您可以简化选择器:
var Tabletr = $(".ChatBox tr:odd")
这为您提供了表中每个奇数行的jQuery对象。如果只有一个这样的行,你可以这样做:
var Tabletr = $('.ChatBox tr:odd')[0].className; // -> "row2"
但是如果有多行,你需要更像这样的东西:
var TableRowClasses = $(".ChatBox tr:odd").map( function(){
return this.className;
}).get();
这为您提供了一个数组,其中每个奇数行的类都是一个元素。所以你最终会得到一个像这样的数组:
["row2","row4","row6"] // confusing odd-row classnames notwithstanding
答案 4 :(得分:0)
我查看了您的代码,以下更改为我提供了结果。
<table id="ChatTable" class="ChatBox" style="margin-left:0px !important">
<tr class="row1">
<td></td>
</tr>
<tr class="row2">
<td></td>
</tr>
<tr class="row3">
<td></td>
</tr>
<tr class="row4">
<td></td>
</tr>
</table>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function () {
$(".ChatBox tr:odd").each(function () {
//test
alert($(this).attr("class"));
});
});
</script>