PHP/Wordpress项目While循环内If语句引发时间线内容重复问题求助
问题原因
你的时间线内容重复问题由两个逻辑不匹配导致:
- 圆点点击事件传递的ID值错误:你在输出圆点时向
ShowTimeline传入的是ACF字段组的自定义ID,该值和时间点的顺序索引没有对应关系,无法匹配到对应的内容区块 - 内容展示逻辑错误:每个时间点对应2个
.hidabletimeline元素(1个放图片、1个放文本),原JS直接用传入的ID取i和i+1的元素,完全对应不上正确的内容区块位置
修复方案
1. 修改PHP循环(输出圆点部分)
给圆点循环添加顺序计数,把正确的顺序索引传给点击事件:
<?php // 添加计数变量初始值 $dot_index = 0; while (have_rows('timeline_points_repeater')) : the_row(); $group_parent = get_sub_field('timeline_point_group'); ?> <div class="col"> <div class="timeline-dot"> <p><?php echo $group_parent['timeline_point_top_text']; ?></p> <!-- 修改onclick传值为顺序索引 --> <img src="<?php echo th_get_img("/timeline/timeline-dot.png") ?>" alt="" id="<?php echo $group_parent['id'] ?>" onclick="HideTimelines();ShowTimeline(<?php echo $dot_index; ?>);"> <p><?php echo $group_parent['timeline_point_bottom_text']; ?></p> </div> </div> <?php // 计数自增 $dot_index++; endwhile; ?>
2. 修改JS展示逻辑
调整索引计算规则,匹配每个时间点对应2个内容块的结构:
function ShowTimeline(idx) { let hidabletimeline = document.getElementsByClassName("hidabletimeline"); // 计算当前时间点对应的两个内容块索引 const imgIndex = idx * 2; const textIndex = idx * 2 + 1; // 加边界判断避免索引越界报错 if (hidabletimeline[imgIndex]) { hidabletimeline[imgIndex].classList.remove("no-display"); } if (hidabletimeline[textIndex]) { hidabletimeline[textIndex].classList.remove("no-display"); } }
内容的提问来源于stack exchange,提问作者ryan
相关产品推荐
相关产品推荐

