I need to generate this 4 JQuery calls inside a Javascript Function:
$(".dropdown-menu .1_147").hover(
function() { $("#1_147").show(); },
function() { $("#1_147").hide(); }
);
$(".dropdown-menu .2_147").hover(
function() { $("#2_147").show(); },
function() { $("#2_147").hide(); }
);
$(".dropdown-menu .3_147").hover(
function() { $("#3_147").show(); },
function() { $("#3_147").hide(); }
);
$(".dropdown-menu .4_147").hover(
function() { $("#4_147").show(); },
function() { $("#4_147").hide(); }
);
I’ve write a Javascript function, the FOR loop only generates the last interaction “4_147”. How can I tell the Javascript to generate the 4 JQuery calls?
My current JavaScript:
var submenu_navigation = document.getElementsByClassName("dropdown-menu");
var submenu_navigation_list = submenu_navigation[0].getElementsByTagName('li');
/*console.log(submenu_navigation_list);*/
function generateDropdownMenuMoldura(lis_array) {
for (var item in lis_array) {
var item_class_attr_name = lis_array[item].getAttribute('class');
console.log(item_class_attr_name);
$(".dropdown-menu ." + item_class_attr_name).hover(
function() { $("#" + item_class_attr_name).show(); },
function() { $("#" + item_class_attr_name).hide(); }
);
}
}
generateDropdownMenuMoldura(submenu_navigation_list);
Any clues?
Best Regards,
Update:
I got the solution:
/* Define the Elements that I need to loop */
var submenu_navigation = document.getElementsByClassName("dropdown-menu");
var submenu_navigation_list = submenu_navigation[0].getElementsByTagName('li');
function generateDropdownMenuMoldura(lis_array) {
for (var item in lis_array) {
var item_class_attr_name = lis_array[item].getAttribute('class');
console.log(item_class_attr_name);
(function(item_class_attr_name) {
$(".dropdown-menu ." + item_class_attr_name).hover(
function() { $("#" + item_class_attr_name).show(); },
function() { $("#" + item_class_attr_name).hide(); }
);
})(item_class_attr_name);
}
}
generateDropdownMenuMoldura(submenu_navigation_list);
My question is: How this anonymous function call works? This is a recursion technique?
Best Regards,
How to fix your specific solution was already answered in an other question.
But why so complicated? Judging from the JavaScript you currently have, and assuming everything apart from the scope works fine, a simpler solution would be:
There is no need to bind a different handler to each of these elements, since they all do basically the same thing.