WordPress站点脚本if语句失效:非首页专属脚本无法正常执行
WordPress非首页脚本失效问题排查
我尝试编写一段仅在WordPress非首页运行的脚本,添加至页面后无法正常工作。移除自行添加的if语句后脚本可正常运行,请问问题出在哪里?
我的代码如下:
<script> jQuery(document).ready(function(){ var totalheight = 0; if (jQuery("body:not(.home)")) { jQuery(".et-l--header .et_builder_inner_content .et_pb_section").each(function(){ totalheight = totalheight + jQuery(this).outerHeight(); }); totalheight = totalheight + "px"; jQuery("#et-main-area").css("padding-top", totalheight); } }); </script>
问题根源
问题出在if (jQuery("body:not(.home)"))这个判断逻辑上:
- jQuery选择器无论是否匹配到元素,都会返回一个jQuery对象,而在JavaScript中,对象属于真值,所以这个if条件永远为
true——哪怕是在首页(body带有.home类),代码也会执行。 - 首页通常没有
.et-l--header .et_builder_inner_content .et_pb_section这类元素,循环计算高度时totalheight会保持为0,最终把#et-main-area的padding-top设为0px,看起来就像脚本没生效;而非首页可能因为其他因素,这个错误判断导致逻辑异常。
修正方案
需要用正确的方式判断当前是否为非首页,推荐两种写法:
写法1:直接判断body是否没有.home类
<script> jQuery(document).ready(function(){ var totalheight = 0; // 检查body不包含home类(即非首页) if (!jQuery("body").hasClass("home")) { jQuery(".et-l--header .et_builder_inner_content .et_pb_section").each(function(){ totalheight = totalheight + jQuery(this).outerHeight(); }); totalheight = totalheight + "px"; jQuery("#et-main-area").css("padding-top", totalheight); } }); </script>
写法2:判断选择器是否匹配到元素
<script> jQuery(document).ready(function(){ var totalheight = 0; // 检查body:not(.home)是否存在(即非首页) if (jQuery("body:not(.home)").length > 0) { jQuery(".et-l--header .et_builder_inner_content .et_pb_section").each(function(){ totalheight = totalheight + jQuery(this).outerHeight(); }); totalheight = totalheight + "px"; jQuery("#et-main-area").css("padding-top", totalheight); } }); </script>
说明
.hasClass("home")是更直接高效的判断方式,专门用于检测元素是否包含指定类名;.length属性用于判断jQuery选择器是否匹配到了至少一个元素,也是常见的判断方式。
两种写法都能正确区分首页与非首页,确保代码只在目标页面执行。
内容的提问来源于stack exchange,提问作者krskaggs13
相关产品推荐
相关产品推荐

