Javascript-使用域名的条件
我已经解决了一个解决方案,使有条件知道如果我不在索引页中,元素的背景图像应该是无的。如何在不需要编写页面域的情况下执行此操作? 比这更好的解决方案:Javascript-使用域名的条件,javascript,Javascript,我已经解决了一个解决方案,使有条件知道如果我不在索引页中,元素的背景图像应该是无的。如何在不需要编写页面域的情况下执行此操作? 比这更好的解决方案: if(window.location.href != 'http://example.com/'){ document.querySelector('.menu-principal') .style.backgroundImage = 'none' } 我只想知道我是否在索引页中,而不需要编写页面域 一个选项是检查location.p
if(window.location.href != 'http://example.com/'){
document.querySelector('.menu-principal')
.style.backgroundImage = 'none'
}
我只想知道我是否在索引页中,而不需要编写页面域 一个选项是检查
location.pathname
,它将保存URL字符串中经过域的所有内容-例如,对于此页面,其URL为
https://stackoverflow.com/questions/53000339/javascript-conditional-using-the-domain-name/53000364
路径名为
/questions/53000339/javascript-conditional-using-the-domain-name/53000364
在索引页上时,即使URL字符串中没有尾随的/
,路径名也是/
。因此,如果您的路径名不是/
,那么您知道您位于索引页之外的其他位置:
if (window.location.pathname !== '/'){
document.querySelector('.menu-principal')
.style.backgroundImage = 'none'
}
使用以下命令:
var { pathname } = window.location;
if (!(pathname == "" || pathname == "/" || pathname == "/index.html")) {
document.querySelector(".menu-principal").style.backgroundImage = "none";
}
因此,以下内容都是索引页,因此背景图像将可见:
https://stackoverflow.com
https://stackoverflow.com/
https://stackoverflow.com/index.html
是的,在使用字符串替换来替换您的scheme://domain.tld/ 使用“”时,您将只剩下资源路径。忽略以下事实,即我使用的是“/”或“/”,它不是问题根源。当我在域名中写“/”时,SO阻止了我的帖子。它阻止了
mysite.com
的一部分,只需更改为example.com
,它就会被接受(希望没问题)