js中if else的优化代码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js中if else的优化代码相关的知识,希望对你有一定的参考价值。
if(i==0)
$("#preview .jqzoom img").attr("src","images/Medical_1/zsq-01s.jpg");
$("#preview .jqzoom img").attr("jqimg","images/Medical_1/zsq-01b.jpg");
else if(i==1)
$("#preview .jqzoom img").attr("src","images/Medical_1/zhushezhen-01s.jpg");
$("#preview .jqzoom img").attr("jqimg","images/Medical_1/zhushezhen-01b.jpg");
else if(i==2)
$("#preview .jqzoom img").attr("src","images/Medical_1/zsq-01s.jpg");
$("#preview .jqzoom img").attr("jqimg","images/Medical_1/zsq-01b.jpg");
else if(i==3)
$("#preview .jqzoom img").attr("src","images/Medical_1/zsq-01s.jpg");
$("#preview .jqzoom img").attr("jqimg","images/Medical_1/zsq-01b.jpg");
else if(i==4)
$("#preview .jqzoom img").attr("src","images/Medical_1/zsq-01s.jpg");
$("#preview .jqzoom img").attr("jqimg","images/Medical_1/zsq-01b.jpg");
else if(i==5)
$("#preview .jqzoom img").attr("src","images/Medical_1/zsq-01s.jpg");
$("#preview .jqzoom img").attr("jqimg","images/Medical_1/zsq-01b.jpg");
else if(i==6)
$("#preview .jqzoom img").attr("src","images/Medical_1/zsq-01s.jpg");
$("#preview .jqzoom img").attr("jqimg","images/Medical_1/zsq-01b.jpg");
请问怎么用数组 或者其他方法优化代码 这样写太臃肿
imgArray = ["zsq-01b.jpg", "zhushezhen-01b.jpg", "zsq-01b.jpg", "zsq-01b.jpg", "zsq-01b.jpg", "zsq-01b.jpg", "zsq-01b.jpg"];
$("#preview .jqzoom img").attr("src", "images/Medical_1/" + srcArray[i])
.attr("jqimg", "images/Medical_1/" + imgArray[i]);
可以随意修改2个数组里的内容。
如果只有i==2的时候不同,就更简单了,拼地址的时候用i==2 ? "zhushezhen-01s.jpg" : "zsq-01s.jpg" 就行了。
参考技术A 厉害了 用switch呢 好像也差不多以上是关于js中if else的优化代码的主要内容,如果未能解决你的问题,请参考以下文章