Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery索引()的问题_Jquery_Jquery Selectors_Indexing - Fatal编程技术网

jQuery索引()的问题

jQuery索引()的问题,jquery,jquery-selectors,indexing,Jquery,Jquery Selectors,Indexing,我一定错过了一些简单的东西。我试图得到元素的索引,但一直得到-1 HTML: index()返回给定元素的索引以及元素列表,而不是父元素中的元素。要查找单击图像的索引,需要查找所有图像,而不是所有图像的父级 你想要这样的东西: // Find all the images in our parent, and then find our index with that set of images var index = $(this).parent().find("img").index(thi

我一定错过了一些简单的东西。我试图得到元素的索引,但一直得到-1

HTML:

index()
返回给定元素的索引以及元素列表,而不是父元素中的元素。要查找单击图像的索引,需要查找所有图像,而不是所有图像的父级

你想要这样的东西:

// Find all the images in our parent, and then find our index with that set of images
var index = $(this).parent().find("img").index(this);
在第二个示例中,您还使用了id选择器而不是类选择器。而不是

$("#rating_boxes").index($(this)); // your way - select by ID
你想要

$(".rating_boxes").index(this); // select by class

如果您想知道评级框的位置,更可靠的方法是使用:

var index = $(this).prevAll('img').size();

即,计算该元素之前的img元素数量。index方法要求您首先选择父元素,然后选择其中的所有img元素。这要快一点。

我倾向于避免在jQuery 1.3.2及以前版本中使用
index()
,因为它感觉使用起来不直观。我只是用

$(this).prevAll().length
获取索引。在
prevAll()
上调用
size()
只会返回
length
属性的值,因此我更喜欢直接使用length并跳过额外的函数调用

比如说,

$("img.ratingbox").hover(function() {
    var index = $(this).prevAll().length;
    alert(index);
    $(this).attr('src', '/img/ratingbox-selected.gif');
}, function() {
    $(this).attr('src', '/img/ratingbox.gif');
});

在jQuery 1.4中,您只需在jQuery对象上调用
index()
,即可获得对象中第一个元素的索引。

如果在该div之前有一个div或section也包含img,则解决方案

var index=$(this).prevAll().length

不会起作用,因为它给出了与使用相同的答案

$(this.index()

适用于上述任何一种情况的解决方案是

var index=$(this.parent().find(“img”).index(this)


我刚刚应用了这两种方法来解决我的问题。

如果可以的话,我会把它提高20次。index()没有意义。
$(this).prevAll().length
$("img.ratingbox").hover(function() {
    var index = $(this).prevAll().length;
    alert(index);
    $(this).attr('src', '/img/ratingbox-selected.gif');
}, function() {
    $(this).attr('src', '/img/ratingbox.gif');
});