如何在jQuery中获取当前选择器的索引值

如何在jQuery中获取当前选择器的索引值,jquery,html,Jquery,Html,我有一个像这样的HTML代码段在正文中 <div class="screen"></div> <div class="screen"></div> 我尝试了$(this).index(),但它返回了-1。文档 $(this).index(); 试试这个 $(".screen").click(function(){ // get this element's index() number alert($(this).

我有一个像这样的HTML代码段在正文中

<div class="screen"></div>
<div class="screen"></div>
我尝试了
$(this).index()
,但它返回了-1。

文档

$(this).index();

试试这个

$(".screen").click(function(){
      // get this element's index() number
        alert($(this).index())
    })
这就行了,

$(".screen").click(function(){
 // get this element's index() number
 alert($(this).index())
});

试试


演示:

我做了,但它正在返回-1elements@AritraHazra制造fiddle@AritraHazra尝试
$(this.index('.screen')可能是您正在使用的jQueryIt应该可以工作:。根据规范,如果选择器找不到元素,您将得到-1,但您没有使用选择器。这是一个完整(最小)的示例吗?索引定位是与一组元素相关的。您正在尝试基于单个元素本身(而不是组)获取该元素的索引。因此,它将返回
-1
。我建议您使用
$(this).parent().children().index(this)
,或者一种简单的方法,如Arun P Johny在下面的回答中所示。@Mr_Green-文档中说
$(this).index()
是完全合法的-“如果没有传递任何参数[…],返回值是[…]第一个元素的位置[…]相对于它的兄弟元素”,演示显示它在事件中确实工作。为什么您会这样想?请确保在绑定事件处理程序时您的元素存在-因此您的代码必须位于div之后或包装在$(function(){…})中;
$(".screen").click(function(){
 // get this element's index() number
 alert($(this).index())
});
$(".screen").click(function(){
      // get this element's index() number
       alert('Index: ' + $('div').index(this));
    })
var $screens = $(".screen").click(function(){
  // get this element's index() number
    alert($screens.index(this))
})