【发布时间】:2020-01-03 19:15:57
【问题描述】:
如何在 à foreach 循环内的 jQuery 代码中定位 ACF 字段?
目前,帖子在 foreach 循环中循环。每篇文章都会展示一位教练,上面有照片、头衔、简短描述和电话号码。所有这些元素都是 ACF 自定义字段,需要在后台为每个人填写。
到此为止就好了。
每个教练的电话号码是隐藏的,用户需要点击一个按钮(这是一个图像“显示号码”)才能看到电话(这也是另一个图像)。我正在使用 .attr() jQuery 函数将第一个图像替换为第二个图像。
问题:当用户点击任何“显示编号”图像时,会显示最后一个图像编号。
期望(例如:Nicolas 为 555-555-555 | Andrea 为 555-485-784 | Melody 为 555-124-332) 目前(例如:Nicolas 为 555-124-332 | Andrea 为 555-124-332 | Melody 为 555-124-332)
任何建议将不胜感激。
谢谢
foreach ($related_posts_articles as $related_post ){
<div class="col-sm-6 col-md-6 col-lg-3 col-xs-12">
<div>
<a href="<?php echo get_permalink($related_post->ID); ?> ">
<?php echo get_the_post_thumbnail($related_post->ID,"square-300",array('class' => 'img-responsive')); ?>
</a>
<div>
<a href="<?php echo get_permalink($related_post->ID); ?>">
<h2>
<?php echo wp_html_excerpt(strip_tags(get_field('acf_titre_mini', $related_post->ID)), 30, '...' ); ?>
</h2>
</a>
<div>
<?php echo wp_html_excerpt( strip_tags(get_field('acf_description_mini',$related_post->ID)), 129, '...' ); ?>
</div>
<!-- START bloc -->
<?php if( get_field('acf_numero_image', $related_post->ID) ): ?>
<div align="center">
<img class="input_img" src="<?php the_field('acf_btnVoirNum_image', $related_post->ID); ?>" >
<script>
jQuery(document).ready(function($) {
$(".input_img").click(function() {
$(this).attr("src", "<?php the_field('acf_numero_image', $related_post->ID); ?>" );
});
});
</script>
</div>
<?php endif; ?>
<!-- END bloc -->
</div>
</div>
</div>
}
【问题讨论】:
-
可能是因为您在
foreach循环中添加了多个$(".input_img").click(function() ...函数。将 JavaScript 移出循环,给.input_img元素一个自定义属性(例如data-acf-numero-image="whatever"),然后将该值用于.attr("src", value)部分。 -
@user7290573 感谢您的消息。在为 .input_img 提供自定义属性时,您的意思是在 jQuery 代码中还是在
类中?在 data-acf-numero-image="whatever" 中可以存储一个 URL(例如 data-acf-numero-image="ID); ?>" ?
-
是的,完全正确 - 尝试更改为
<img class="input_img" src="<?php the_field('acf_btnVoirNum_image', $related_post->ID); ?>" data-acf-numero-image="<?php the_field('acf_numero_image', $related_post->ID); ?>" />,然后为您的图像使用 one.click()处理程序。 -
@user7290573 好的 - 我试过这个:ID); ?>" data- acf-numero-image="ID); ?>" onclick="input_img[this.dataset.acfNumeroImage];"> 但没有结果。当您说只使用一个“.click()”时,它意味着在 img 标记中而不是在 jQuery 代码中,对吗?我认为我在语法上做错了什么。
-
为了清楚起见,我已经发布了一个答案。
标签: jquery advanced-custom-fields attr