在我的jQuery为什么indexOf没有找到关键从我的数组

In my jQuery why indexOf does not find key from my array?

本文关键字:我的 数组 jQuery 为什么 indexOf      更新时间:2023-09-26

我一直在试着让它工作,但似乎没有什么帮助。

我有两张图片都在图片数组中。我想做的是,当你点击上一张图片时,下一张就会出现。我很确定问题出在indexOf上,因为它每次都返回-1。

如果我替换line:

pictures[listIndex+1].show("drop", {direction: "up"}, 1000); <——不工作

:

pictures[1].show("drop", {direction: "up"}, 1000); <——它工作,但不是很有用。

我希望你能理解我的问题是什么,并为我糟糕的英语感到抱歉。我真的很感激你的帮助。

$(document).ready(function(){
    var pictures = [$("#link"), $("#italy1")];
    pictures[1].hide();
    $("#link").click(function(){
        var listIndex = pictures.indexOf($(this));
        pictures[listIndex+1].show("drop", {direction: "up"}, 1000);
    });
    $("#italy1").click(function(){
        $(this).hide("drop", {direction: "up"}, 1000);
});
});

这是因为您在jQuery对象中包装元素。即使两个jQuery对象包含相同的元素,它们仍然是两个独立的对象,所以indexOf方法不能通过寻找另一个来找到一个。

将元素本身放入数组中:

var pictures = [$("#link").get(0), $("#italy1").get(0)];

现在可以使用元素引用来查找数组中的元素。使用$.inArray方法,因为它也适用于没有Array.indexOf方法的浏览器:

var listIndex = $.inArray(this, pictures);

当然,当您从数组中获得元素时,您需要将其包装在jQuery对象中,以便对其使用jQuery方法:

$(pictures[listIndex+1]).show("drop", {direction: "up"}, 1000);

可能是jQuery。

如果您想选择下一个$("#link"),您可以始终使用 $(this).next("#link")

为了支持Guffa,像这样的东西。

$(document).ready(function(){
    var pictures = [$("#link").get(0), $("#italy1").get(0)];
    $(pictures[1]).hide();
    $("#link").on('click', function(){
        var listIndex = $.inArray(this, pictures);
        $(pictures[listIndex+1]).show("drop", {direction: "up"}, 1000);
    });
    $("#italy1").on('click', function(){
        $(this).hide("drop", {direction: "up"}, 1000);
    });
});