Could someone tell me why in the first alert(items.index($(this))) = 1 and the second alert(items.index($(this))) = -1. How does this value get changed within the other function?
$(function () {
var items = $('#v-nav>ul>li').each(function () {
$(this).click(function () {
//remove previous class and add it to clicked tab
items.removeClass('current');
$(this).addClass('current');
alert(items.index($(this)));
$('#v-nav>div.tab-content').fadeOut("slow", function () {
alert(items.index($(this)));
$('#v-nav>div.tab-content').eq(items.index($(this))).fadeIn("slow");
});
// window.location.hash = $(this).attr('tab');
});
});
thisrefers to current object.In first version,
thisis an item of$('#v-nav>ul>li')list.While in second version,
thisis DOM object selected by$('#v-nav>div.tab-content')If you want to retain the previous value of
this, then cache it in a variable.(Caching
$(this)is a very good practise, as you always save a function call).When you use
$(this)you actually passesthisinto$function.