I'm building a website in asp.net and just started to learn javascript.
I'm trying to make a little dynamic menu so when you click on a tab, it will show and hide the menus.
On the tabs, the links (a) have an attribute called target_menu which hold the menu name. The menus have an attribute called menu, which of course holds its name.
In my javascript, on jquery.ready I have it create the onclick events for each tab, but every time I click a tab they all seem to be using the target_menu attribute from the last item in the list.
Here is my code.
$(document).ready(function () {
var navItems = $("a[target_menu]");
for (var i = 0; i < navItems.length; i++) {
var t = $(navItems[i]).attr('target_menu');
//When this isn't commented it will display each item of the list correctly.
//alert(t);
//But when this is called its only giving me the last item in the list.
navItems[i].onclick = function () { EnableMenu(t.toString()); };
//$(navItems[i]).on('click', function () { EnableMenu($(navItems[i]).attr('target_menu')); });
}
var target = $("a.active[target_menu]").attr('target_menu');
ToggleMenu(target);
});
function EnableMenu(menu)
{
alert(menu);
$("a[target_menu]").removeClass('active');
$("a[target_menu='" + menu + "']").addClass('active');
ToggleMenu($("a[target_menu='" + menu + "']").attr('target_menu'));
}
function ToggleMenu(target)
{
$("[menu='" + target + "']").show();
$("[menu][menu!='" + target + "']").hide();
}
I thought it may have something to do with passing the variable t, and setting it each time in the loop, so I added the .tostring() but am still getting the same issue. When I didn't use t I kept getting undefined, and I couldn't get the jquery on('click'... to work at all.
So even though I used .tostring() when onclick is called it still seems to be referencing the t variable, and converting it to a string, instead of just passing it.