[英]Conditionally hide div on all posts but not category page
如何在除WordPress类别页面上的帖子之外的所有帖子上隐藏div?
我目前有以下jQuery但无法让它工作 -
jQuery(function(){
if (window.location.pathname == "offonalim.com/category/fashion.html"||window.location.pathname == "offonalim.com/category/interior.html"||window.location.pathname == "offonalim.com/category/travel.html"||window.location.pathname == "offonalim.com/category/work.html") {
jQuery('.qodef-post-title').show();
jQuery('.qodef-post-info').show();
} else {
jQuery('.qodef-post-title').hide();
jQuery('.qodef-post-info').hide();
}
});
我可以看到您网站的类别页面在每个网址中都包含关键字"Category"
,因此您可以使用此关键字检查网址是否包含此特定关键字,然后相应地显示或隐藏div
无需指定完整的URL。
<script type="text/javascript">
function myFunction(){
val path=window.location.pathname;
if(window.location.href.indexOf("category") > -1) {
$('.qodef-post-title').show();
$('.qodef-post-info').show();
} else {
$('.qodef-post-title').hide();
$('.qodef-post-info').hide();
}
}
myFunction();
</script>
window.location.pathname
产生路径名,而不是整个URL。 因此,您的代码在逻辑上是不正确的。
而不是单独检查每个路径,理想的做法是创建一个可能的路径数组并检查该数组中的位置路径。 像这样的东西应该工作正常:
var catPaths = [
"/category/fashion.html",
"/category/interior.html",
"/category/travel.html",
"/category/work.html"
];
jQuery(function() {
if (catPaths.includes(window.location.pathname)) {
jQuery('.qodef-post-title').show();
jQuery('.qodef-post-info').show();
} else {
jQuery('.qodef-post-title').hide();
jQuery('.qodef-post-info').hide();
}
});
您可以通过使用toggle()
和分组选择器来进一步最小化代码:
jQuery(function() {
var includes = catPaths.includes(window.location.pathname);
jQuery('.qodef-post-title, .qodef-post-info').toggle(includes);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.