如何使用jQuery在Div(产品)中获取类(headerGrid)的特定实例。
我需要能够获得类“headerGrid”类别span的实例,其中写着“获取此文本”。该实例表示为swap2()中的值。我的代码如下......
<table id="products">
...
<tr>
<td>
<a onclick="swap2(1);"><img src="images/products/thumbs/image.png"/></a>
</td>
<td valign="top" class="product-text">
<span class="headerGrid">Get this Text</span><br /><br />
text
</td>
</tr>
...
</table>
E.g。如果 onclick =“swap2(5);”那么我需要得到'.headerGrid'的第5个实例
修改的
更多我需要选择文本(“获取此文本”)而不是对象本身。另外,它返回对象[object Object]。
我也尝试选择 .innerHTML ,它返回 undefined。
答案 0 :(得分:4)
$('#products span.headerGrid:nth-child(5)')
答案 1 :(得分:4)
使用eq()
selector。例如:
$("#products span.headerGrid").eq(4) //Zero based index
使用您的功能:
function swap2(n) {
//Zero based index, subtract 1
var theText = $("#products span.headerGrid").eq(n - 1).html();
...
}
答案 2 :(得分:3)
使用$("#products span.headerGrid:nth-child(5)")
,它会在ID为headerGrid
的元素中返回带有products
类的第5个范围。
函数交换可能如下所示:
function swap(n){
var element = $("#products span.headerGrid:nth-child(" + n + ")");
//Rest of code
}
小通知:您在问题中提到过DIV(products)
,但您的代码显示为table
。