Optimize jQuery

What would be the best way to optimize (shorten) this block of code ?. I use the Jquery UI plugin 'select menu' to assign the selected number of items.

$('footer#footer form select').selectmenu({ style: 'dropdown', appendTo: 'footer#footer form span' }); $('form.filters section.grid .industry select').selectmenu({ style: 'dropdown', appendTo: 'form.filters section.grid .industry' }); $('form.filters section.grid .subject select').selectmenu({ style: 'dropdown', appendTo: 'form.filters section.grid .subject' }); $('form.filters section.grid .year select').selectmenu({ style: 'dropdown', appendTo: 'form.filters section.grid .year' }); $('form.filters section.grid .organiser select').selectmenu({ style: 'dropdown', appendTo: 'form.filters section.grid .organiser' }); 
+4
source share
2 answers

You can display the “selectors” in the “add” part

 var parts = { 'footer#footer form select' : ' span', 'form.filters section.grid .industry select' : '', 'form.filters section.grid .subject select' : '', 'form.filters section.grid .year select' : '', 'form.filters section.grid .organiser select': '' }; for (var p in parts) { $(p).selectmenu({ style: 'dropdown', appendTo: p.replace(" select", parts[p]) }); } 

Or you could do it.

 $('footer#footer form select').selectmenu({ style: 'dropdown', appendTo: 'footer#footer form select span' }); $('form.filters section.grid .row * select').each(function() { $(this).selectmenu({ style: 'dropdown', appendTo: $(this).closest('.span3') }); }); 
+1
source

Use the classes and attributes [data-*] to pass data to jQuery:

 $('select.selectMenu').each(function () { $(this).selectmenu({ style: 'dropdown', appendTo: $(this).data('target') }); }); 

It depends on the markup changes, so the selection elements have the correct class and have the [data-target] attributes set for the corresponding values.

 <select class="selectMenu" data-target="footer#footer form span"> ...options... </select> 

Several options for each and HTML body:

Using the whole data object:

 $(this).selectmenu($(this).data()); <select data-style="dropdown" data-append-to="footer#footer form span"> 

Using a single attribute [data-*] :

 $(this).selectmenu($(this).data('selectmenu')); <select data-selectmenu='{"style":"dropdown","appendTo":"footer#footer form span"}'> 
+2
source

Source: https://habr.com/ru/post/1436390/


All Articles