Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to replace 'if' statement with 'switch' statement in jquery

I have some page with multiple pup-ups on it, so when user clicks on preview – correct full picture appear. This is html:

    <tr class="rowLicense">
 <td class="bigPop licensePopUp" ><img src="images/license/license_1.jpg"></td>
 <td class="bigPop licensePopUp2"><img src="images/license/license_2.jpg"></td>
 <td class="bigPop licensePopUp3"><img src="images/license/license_3.jpg"></td>
    </tr>

This is the 'if' version of the script:

 $(".bigPop").click(function(){
            if ($(this).is(".licensePopUp")){ //заменить на свитч
                $(".popupLicense").fadeIn();
           }
            else if ($(this).is(".licensePopUp2"))  {
                $(".popupLicense2").fadeIn();
            }
            else if ($(this).is(".licensePopUp3"){
                     $(".popupLicense2").fadeIn();
            }
        });

it works, but seems not optimal

I tried to use 'switch', this is the code:

  $(".bigPop").click(function(){
              var i = $(this).is();
                switch (i) {
                    case (".licensePopUp"): 
                         $(".popupLicense").fadeIn();
                    break;
                    case (".licensePopUp2"):
                        $(".popupLicense2").fadeIn();
                    break;
                          }

        });

It does not work, i suppose i did some mistakes in defining 'i', or maybe in declaring statement, but i cant find a clue.

P.S. Please don't blame me, i just started to learn js, so don't know many obvious things.

like image 662
Fedor Avatar asked Jun 11 '26 09:06

Fedor


1 Answers

You could simplify your code significantly if you used some sort of data attribute which would target specific popup:

<td class="bigPop" data-target=".licensePopUp"><img src="images/license/license_1.jpg"></td>
<td class="bigPop" data-target=".licensePopUp2"><img src="images/license/license_2.jpg"></td>
<td class="bigPop" data-target=".licensePopUp3"><img src="images/license/license_3.jpg"></td>

And JS then:

$(".bigPop").click(function () {
    $($(this).data('target')).fadeIn();
});

This approach offers additional flexibility, because now data-target can be any CSS selector, not only class name, but also id, etc.

like image 64
dfsq Avatar answered Jun 13 '26 21:06

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!