Please tell me how to simplify the script

<div id="block4"> <ul> <li class="tb1">1</li> <li class="tb2">2</li> <li class="tb3">3</li> </ul> </div> $('.tb1').click(function() { $('#block4').removeClass().addClass('tabFon1'); }); $('.tb2').click(function() { $('#block4').removeClass().addClass('tabFon2'); }); $('.tb3').click(function() { $('#block4').removeClass().addClass('tabFon3'); }); 
  • 2
    You can replace the same type of code with a function call. - KoVadim

4 answers 4

Accidentally read here about the new feature let

 for(let i = 1; i <= 3; i++){ $('.tb' + i).click(function() { $('#block4').removeClass().addClass('tabFon' + i); }); } 

    The class to be assigned can be assembled from the name of the class li clicked.

    For example:

     $('li').click(function() { $('#block4').removeClass().addClass('tabFon' + this.className.match(/\d/)); }); 
     .tabFon1 { border: 1px solid red; background-color: red; } .tabFon2 { border: 1px solid green; background-color: green; } .tabFon3 { border: 1px solid blue; background-color: blue; } li { border: 1px solid black; background-color: white; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="block4"> <ul> <li class="tb1">1</li> <li class="tb2">2</li> <li class="tb3">3</li> </ul> </div> 

       $('#block4 ul li').click(function() { var n = $(this).attr('class').match(/\d+/); $('#block4').removeClass().addClass('tabFon' + n); }); 

        you can still try this

         for(var i = 1; i <= $('li').length; i++){ $('.tb'+i).click((function(i){ return function () { $('#block4').removeClass().addClass('tabFon'+i) } } )(i))}