如何在下面的代码中获取点击项目的索引?
$('selector').click(function (event) {
// get index in collection of the clicked item ...
});
使用 Firebug 我看到了这个:(jQuery151017197709735298827: 2
我点击了第二个元素)。
如何在下面的代码中获取点击项目的索引?
$('selector').click(function (event) {
// get index in collection of the clicked item ...
});
使用 Firebug 我看到了这个:(jQuery151017197709735298827: 2
我点击了第二个元素)。
这将提醒单击的选择器的索引(第一个从 0 开始):
$('selector').click(function(){
alert( $('selector').index(this) );
});
$('selector').click(function (event) {
alert($(this).index());
});
$(this).index()
如果元素是兄弟元素,则可用于获取单击元素的索引。
<div id="container">
<a href="#" class="link">1</a>
<a href="#" class="link">2</a>
<a href="#" class="link">3</a>
<a href="#" class="link">4</a>
</div>
如果没有参数传递给该
.index()
方法,则返回值是一个整数,指示 jQuery 对象中第一个元素相对于其兄弟元素的位置。
将选择器传递给index(selector)
.
$(this).index(selector);
例子:
找到<a>
被点击的元素的索引。
<tr>
<td><a href="#" class="adwa">0001</a></td>
</tr>
<tr>
<td><a href="#" class="adwa">0002</a></td>
</tr>
<tr>
<td><a href="#" class="adwa">0003</a></td>
</tr>
<tr>
<td><a href="#" class="adwa">0004</a></td>
</tr>
就这样做: -
$('ul li').on('click', function(e) {
alert($(this).index());
});
或者
$('ul li').click(function() {
alert($(this).index());
});
看看这个 https://forum.jquery.com/topic/get-index-of-same-class-element-on-click 然后 http://jsfiddle.net/me2loveit2/d6rFM/2/
var index = $('selector').index(this);
console.log(index)