Hello, help simplify this code, shorten lines, write to one function ... thank you for your help :)

$(document).ready(function () { $("#hide-1").show(); $("#hide-2").hide(); $("#hide-3").hide(); $("#hide-4").hide(); $("#li-1").click(function () { $("#hide-1").show(); $("#hide-2").hide(); $("#hide-3").hide(); $("#hide-4").hide(); }); $("#li-2").click(function () { $("#hide-2").show(); $("#hide-1").hide(); $("#hide-3").hide(); $("#hide-4").hide(); }); $("#li-3").click(function () { $("#hide-3").show(); $("#hide-2").hide(); $("#hide-1").hide(); $("#hide-4").hide(); }); $("#li-4").click(function () { $("#hide-4").show(); $("#hide-2").hide(); $("#hide-3").hide(); $("#hide-1").hide(); }); }); 
  • Give markup. Classes everything is solved, but you need to know how the buttons are located relative to the blocks that you want to hide / show. - Yura Ivanov

2 answers 2

There is no need to simplify the code, but to change the approach to solving the problem. Here you have sketched an example, it is not perfect, but it will give food for thought - http://jsfiddle.net/3wbnqv8m/

  • Thank you so much - David Kern

According to your code, you can do this, suddenly you will not change ...
1. All #hide-1,#hide-2,#hide-N assign the class hide-all
2. Click to catch on the element itself or the general class.

 $(document).ready(function () { $(".hide-all").hide(); $("#hide-1").show(); /// id: #li-1,#li-2,....#li-N $("li").click(function (){ var id = this.id.replace(/[^0-9.]/g,""); $(".hide-all").hide(); $("#hide-"+id).show(); }); }); 

Well, it's better to listen to @andreyqin