1

So I'm trying to get the number of the li that I click and show the corresponding page text while hiding the others. (labeled #text1, #text2, #text3 etc...), but the code below isn't doing anything for me.

Help is greatly appreciated!

var j = 0;
$(".gallery li").each(function () {
    j++;

    $(".gallery li").click(function () {
        var num = $(this).index() + 1;
        $('#text' + num).addClass('currentpage');
        $('#text' + num).siblings().removeClass('currentpage');
    });
});
4

3 回答 3

3

See this working fiddle. You just need to take out the .each

$(".gallery li").click(function () {
    var num = $(this).index() + 1;
    $('#text' + num).addClass('currentpage');
    $('#text' + num).siblings().removeClass('currentpage');
});
于 2013-06-27T19:45:55.287 回答
2

Try

var num = $('li').index(this) + 1;

instead of

var num = $(this).index() + 1;

And remove the each loop

$(".gallery li").click(function () {
     var num = $('.gallery li').index(this) + 1;
     $('#text' + num).addClass('currentpage');
     $('#text' + num).siblings().removeClass('currentpage');
});

Should be good enough

And better .. You need not use the index in the first place

$(".gallery li").click(function () {
    $(this).addClass('currentpage');
    $(this).siblings().removeClass('currentpage');
});

You can just use the this context directly in your code as that corresponds to the current li that is selected.

于 2013-06-27T19:40:43.107 回答
0

I'm not sure what you're doing... but you can do this:

Throw in index and value as the parameters of the closure for each. Example: $(".gallery li").each( function(index, value){ - then you can use index instead of j

于 2013-06-27T19:41:53.393 回答