我正在尝试缩短我创建的一系列if / else语句。该代码可以正常工作,但目前看来是多余的。我试图实现一个循环来执行此操作,但我不知道如何处理循环中每个语句的“ indexOf(“”)“。
这是我的代码:
window.addEventListener("load", (event)=>{
$("div.faq-container").hide();
if (window.location.href.indexOf("shipping") > -1) {
$("div.faq-container").eq( "0" ).show();
}
else if (window.location.href.indexOf("returns") > -1) {
$("div.faq-container").eq( "1" ).show();
}
else if (window.location.href.indexOf("custom") > -1) {
$("div.faq-container").eq( "2" ).show();
}
else if (window.location.href.indexOf("replacements") > -1) {
$("div.faq-container").eq( "3" ).show();
}
else if (window.location.href.indexOf("mostFAQs") > -1) {
$("div.faq-container").eq( "4" ).show();
}
else if (window.location.href.indexOf("RAD") > -1) {
$("div.faq-container").eq( "5" ).show();
}
else if (window.location.href.indexOf("environmental") > -1) {
$("div.faq-container").eq( "6" ).show();
}
else if (window.location.href.indexOf("USA") > -1) {
$("div.faq-container").eq( "7" ).show();
}
else{
$("div.faq-container").eq( "0" ).show();
}
})
有什么建议?
您可以只对每个值使用一个数组,数组也使用零索引,因此您可以在数组中使用indexOf来获取索引。
例如。
const lu = ['shipping', 'returns', 'custom', 'replacements',
'mostFAQs', 'RAD', 'environmental', 'USA'
];
window.addEventListener("load", (event)=>{
$("div.faq-container").hide();
for (let ix = 0; ix < lu.length; ix += 1) {
if (window.location.href.indexOf(lu[ix]) > -1) {
$("div.faq-container").eq(ix.toString()).show();
return;
}
}
$("div.faq-container").eq( "0" ).show();
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句