gpt4 book ai didi

javascript - 无法在 jquery 中用 'if' 语句替换 'switch' 语句

转载 作者:可可西里 更新时间:2023-11-01 13:09:33 25 4
gpt4 key购买 nike

我有一些页面上有多个弹出窗口,所以当用户点击预览时——会出现正确的完整图片。这是 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();
}
});

它有效,但似乎不是最优的

我尝试使用'switch',这是代码:

  $(".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();
});

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

关于javascript - 无法在 jquery 中用 'if' 语句替换 'switch' 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26830319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com