无法替换'如果'带有'交换机'jquery中的语句

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

本文关键字:jquery 语句 交换机 如果 替换 带有      更新时间:2023-09-26

我有一个页面,上面有多个pu-up,所以当用户点击预览时,会出现正确的完整图片。这是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>

这是脚本的"if"版本:

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

它有效,但似乎不是最佳

我试着用"开关",这是代码:

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

它不起作用,我想我在定义"i"或声明语句时犯了一些错误,但我找不到线索。

附言:请不要责怪我,我刚开始学习js,所以不知道很多显而易见的事情。

如果您使用某种针对特定弹出窗口的数据属性,您可以显著简化代码:

<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>

然后JS:

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

这种方法提供了额外的灵活性,因为现在data-target可以是任何CSS选择器,不仅可以是类名,还可以是id等。

您可以这样做,而不需要任何ifswitch

$(".bigPop").click(function() {
    var num = $(this).attr("class").replace(/.*licensePopUp('d).*/, "$1");
    $('.popupLicense' + (num ? num : '')).fadeIn();
});

上面的操作是获取类中的数字,然后将其与该数字连接,或者如果该数字不是数字,则只使用空字符串。或者,您可以设置一个单独的data-*属性,然后使用该属性。

这个怎么样?我试图使用event.target.

 $(".bigPop").click(function(event){
          var target = $( event.target );
          target.fadeIn();
 });

注意,我还没有测试代码。

尝试使用如下开关:

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