jQuery('table tr td').each(function() {
console.log ( this );
});
在上面的例子中,console.log(this);打印:
<td valign="top">
Color: Blue<br>
Size: M<br>
<div>Qty: 2</div>
<div>Price: $14.95</div>
</td>
如何从“this”获取当前选择器,即“table tr td”?
我尝试使用console.log(jQuery(this).selector);但它什么都不打印。
答案 0 :(得分:0)
例如,您可以为每个<td>
添加不同的类属性。
$('table tr td').each(function() {
alert($(this).attr("class"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="t1">Color: Blue<br>
Size: M<br>
<div>Qty: 2</div>
<div>Price: $14.95</div></td>
</tr>
<tr>
<td class="t2">Color: Red<br>
Size: L<br>
<div>Qty: 3</div>
<div>Price: $15.99</div></td>
</tr>
<tr>
<td class="t3">Color: Yellow<br>
Size: M<br>
<div>Qty: 2</div>
<div>Price: $14.95</div></td>
</tr>
<tr>
<td class="t4">Color: LightBlue<br>
Size: M<br>
<div>Qty: 4</div>
<div>Price: $12.95</div></td>
</tr>
</table>
答案 1 :(得分:0)
然后尝试以下
var i = 1;
$('table tr td').each(function() {
$(this).addClass("t" + i);
alert($(this).attr("class"));
i++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
<tr>
<td>Color: Blue<br>
Size: M<br>
<div>Qty: 2</div>
<div>Price: $14.95</div></td>
</tr>
<tr>
<td>Color: Red<br>
Size: L<br>
<div>Qty: 3</div>
<div>Price: $15.99</div></td>
</tr>
<tr>
<td>Color: Yellow<br>
Size: M<br>
<div>Qty: 2</div>
<div>Price: $14.95</div></td>
</tr>
<tr>
<td>Color: LightBlue<br>
Size: M<br>
<div>Qty: 4</div>
<div>Price: $12.95</div></td>
</tr>
</table>