在目标上点击一个数组的项目? [英] Target items in an array on click?

查看:144
本文介绍了在目标上点击一个数组的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请记住我是一个JavaScript / jQuery的/计算器新手。我有JQuery的对象的阵列(每一个是一个图像)。现在我有一个单独的函数为阵列中的每个项目:

Bear in mind I'm a javascript/jquery/stackoverflow newbie. I have an array of JQuery objects (each one is an image). Right now I've got a separate function for each item in the array:

var $photos = [];
$photos.push($('img.one'), $('img.two'), $('img.three'), $('img.four'), $('img.five'),              $('img.six'));
$('.thumbnails img.two').click(function(){
    $('div#slide-container').fadeIn('fast');
    setTimeout(function(){
    $('div#slideshow').slideDown('fast');}, 200);
    setTimeout(function(){
    images[1].fadeIn('fast');}, 500);
});

在换句话说我具有上述code表示每个阵列中的5的索引。我怎么能写这样我就可以只用一个函数,而不是6的目标是点击任何照片么?因此,而不是图像[1]具体来说,我只能说图像[我]。

In other words I have the above code for each of the 5 indexes in the array. How can I write this so that I can target whichever photo is clicked using just one function instead of six? So instead of "images[1]" specifically, I can just say "images[i]".

下面是这方面的一个真人版的链接:

Here's a link to a live version of this:

http://www.noticeeverything.com/photos/

推荐答案

您可以编写一个通用的点击处理程序的所有图像,使用 $(本)指元素点击。为了使它在的setTimeout 回调可用,你需要一个局部变量设置为它,所以它会被保存在封闭

You can write a general click handler for all the images that uses $(this) to refer to the element clicked on. To make it available in the setTimeout callback, you'll need to set a local variable to it, so it will be saved in the closure.

$(".thumbnails img").click(function() {
    var $this = $(this);
    $('div#slide-container').fadeIn('fast');
    setTimeout(function() {
        $('div#slideshow').slideDown('fast');
    }, 200);
    setTimeout(function() {
        $this.fadeIn('fast');
    }, 500);
});

更新:

有没有需要的阵列。这个版本只是假定,在幻灯片中的图像是在相同的位置含有相应的缩略图达阵,并使用 .EQ()找到他们。

There's no need for the array. This version just assumes that the images in the slideshow are in the same position as the TDs containing the corresponding thumbnails, and uses .eq() to find them.

$("#thumbnails img.thumb").click(function () {
    var index = $(this).closest('td').index();
    $('div#slide-container').fadeIn('fast');
    setTimeout(function () {
        $('div#slideshow').slideDown('fast');
    }, 200);
    setTimeout(function () {
        $("div#slideshow img").eq(index).fadeIn('fast');
    }, 500);
});

演示

究其原因 $(本)没有被先前设置是因为你有 .thumbnails ,和我复制的,但它应该是 #thumbnails 。所以选择未匹配的元素

The reason $(this) wasn't being set earlier is because you had .thumbnails, and I copied that, but it should be #thumbnails. So the selector wasn't matching the elements.

这篇关于在目标上点击一个数组的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆