我创建了一个函数来每秒检查网站的当前 URL 并更改 <head>
中的元标记图像。 HTML 元素根据一定的值字符串。我的代码是完美的,但是我想让我的代码更具可读性 7 优化...所以我想把这段代码变成 switch 语句,但我现在无法自己弄清楚。
代码如下:
// Variable declarations
var imgOgSrc = $('meta[property="og:image"]');
var twitterImgSrc = $('meta[name="twitter:image:src"]');
var currentUrl;
// Checks for current url & changes meta tags depending on slug value
function getCurrentUrl(){
currentUrl = window.location.href;
if(currentUrl.toLowerCase().indexOf('python') >= 0) {
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
} else if (currentUrl.toLowerCase().indexOf('java') >= 0) {
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
} else if (currentUrl.toLowerCase().indexOf('php') >= 0) {
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
}
else {
imgOgSrc.attr('content', currentUrl);
twitterImgSrc.attr('content', currentUrl);
}
}
最佳答案
由于所有 if
条件都有相同的代码,您可以使用 some
像这样。
function getCurrentUrl() {
currentUrl = window.location.href;
const customUrlNeeded = ['python', 'java', 'php'].some(a => currentUrl.toLowerCase().includes(a))
if (customUrlNeeded) {
imgOgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
twitterImgSrc.attr('content', 'http://carrieres.nameofwebsite.com/static/img/custom-img.jpg');
} else {
imgOgSrc.attr('content', currentUrl);
twitterImgSrc.attr('content', currentUrl);
}
}
关于javascript - 如何将此 else if 语句转换为 switch 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54598349/