What is the shortest way to do this in jquery?

Here is what I have, and everything works fine, but could you tell me if there is a short and clean coding way for this?

$(document).ready(function() { $('span#paylas_').click(function() { $('#uyri').slideUp(); $('#dhda').slideUp(); $('#pyls').slideToggle('normal'); }); $('span#uyari_').click(function() { $('#pyls').slideUp(); $('#dhda').slideUp(); $('#uyri').slideToggle('normal'); }); $('span#dahada_').click(function() { $('#pyls').slideUp(); $('#uyri').slideUp(); $('#dhda').slideToggle('normal'); }); }); 
+4
source share
4 answers

If you give data-toggle attributes for your elements as follows:

 <span id="paylas_" data-toggle="#pyls"></span> 

then you can combine the selector and use .data("toggle") to get the corresponding selector:

 $(document).ready(function() { var toggles = {}; $('#paylas_, #uyari_, #dahada_').click(function() { var cached = this.id in toggles; if(!cached) { toggles[this.id] = $(this).data("toggle"); } var toggle = toggles[this.id]; $('#uyri, #dhda, #pyls').not(toggle).slideUp(); $(toggle).slideToggle('normal'); }); }); 

If you use data-toggle only for these elements, you can also do:

 $('[data-toggle]').click(function() { 

I cannot compose something from identifiers, but if there is a certain structure, you could also generalize the second list of selectors.

+6
source
 $(function() {//notice the shorter document.ready declaration :) //setup a conversion from the clicked elements to the elements to slide up/down var convert = { paylas_ : '#pyls', uyari_ : '#uyri', dahada_ : '#dhda' }; //select all the spans and bind the event handler to them, you can select multiple elements at once by separating the selectors with commas $('#paylas_, #uyari_, #dahada_').click(function() { //slide up all the spans except for the on associated with the currently clicked element $('#uyri, #dhda, #pyls').not(this).slideUp(); //slide toggle the currently clicked element $(convert[this.id]).slideToggle('normal'); }); }); 

Here is a demo: http://jsfiddle.net/yPxHq/1/

+2
source

I think this is the cleanest way without HTML binding:

 $(document).ready(function() { $("#paylas_, #uyari_, #dahada_").click(function() { var ids = ["#uyri", "#dhda", "#pyls"], current = "#" + $(this) .attr("id") .replace(/_$/, "") .replace(/a(.)/g, "$1"); delete ids[$.inArray(current, ids)]; $(ids.join(",")).slideUp(); $(current).slideToggle("normal"); }); }); 

Edit: removed span in front

+2
source

This is a quick refactor that can help a little.

  $(document).ready(function() { clickFuntion("paylas","uyri","dhda","pyls"); clickFuntion("uyari","pyls","dhda","uyri"); clickFuntion("dahada","pyls","uyri","dhda"); function clickFuntion(var1,va2,var3,var4){ $('span#"+var1+"_').click(function() { $('#"+var2+"').slideUp(); $('#"+var3+"').slideUp(); $('#"+var4+"').slideToggle('normal'); }); } }); 
+1
source

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


All Articles