Home >Web Front-end >JS Tutorial >JavaScript code to create dynamic menus or drop-down lists
This time I will bring you the JavaScript code to create a dynamic menu or drop-down list. The precautions for using JavaScript to create a dynamic menu or drop-down list are Which ones, the following are practical cases, let’s take a look.
In many scenarios, we need to dynamically create menus, drop-down lists or list items. The following is the most basic code to implement the above function. You can extend it according to actual needs.
function makeMenu(items, tags) { tags = tags || ['ul', 'li']; // default tags var parent = tags[0]; var child = tags[1]; var item, value = ''; for (var i = 0, l = items.length; i < l; i++) { item = items[i]; // Separate item and value if value is present if (/:/.test(item)) { item = items[i].split(':')[0]; value = items[i].split(':')[1]; } // Wrap the item in tag items[i] = '<'+ child +' '+ (value && 'value="'+value+'"') +'>'+ // add value if present item +'</'+ child +'>'; } return '<'+ parent +'>'+ items.join('') +'</'+ parent +'>'; }
How to use:
// Dropdown select monthmakeMenu( ['January:JAN', 'February:FEB', 'March:MAR'], // item:value ['select', 'option'] ); // List of groceriesmakeMenu( ['Carrots', 'Lettuce', 'Tomatos', 'Milk'], ['ol', 'li'] );
The above are just a small part of those practical JavaScript code snippets. It is recommended to collect or write such basic code snippets yourself. They can be used in many projects. Or provide more complete functions through some modifications. Using these code snippets will save you a lot of development time.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese website Other related articles!
Recommended reading:
JavaScript code snippet to determine whether a date is valid
Get the maximum width or height of a set of elements JavaScript code
The above is the detailed content of JavaScript code to create dynamic menus or drop-down lists. For more information, please follow other related articles on the PHP Chinese website!