我在WordPress网站上通过ACF重复字段有一个重复字段:
<?php
if( have_rows('recent_episodes') ):
$i = 1;
while ( have_rows('recent_episodes') ) : the_row();
$image = get_sub_field('video_image');
?>
<!--API CODE HERE-->
<li class="recent-episode-<?php the_sub_field('brightcove_video_id'); ?> col-md-3 col-sm-4">
<a href="#">
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>">
<div class="flex-caption">
<h6 class="date"><?php the_sub_field('air_date') ?></h6>
<h5 class="title"></h5>
</div>
</a>
</li>
<?php
$i++;
endwhile; else :
endif;
?>
brightcove_video_id字段是用于brightcove中的视频的视频id。理想情况下,我想在重复字段中为每个视频插入相应的标题。当我把API代码放在重复区域时,它每次只输出最后一项。以下是我为API代码所做的:
var token = "HIDDEN";
var req = "http://api.brightcove.com/services/library?"
req += "command=find_video_by_id&token=" + encodeURIComponent(token);
req += "&video_id=" + videoID;
req += "&video_fields=id%2Cname%2CshortDescription%2CreferenceId&media_delivery=default//";
req += "&callback=response";
// Create a new request object
bObj = new JSONscriptRequest(req);
// Build the dynamic script tag
bObj.buildScriptTag();
// Add the script tag to the page
bObj.addScriptTag();
function response(jsonData) {
jQuery('li.recent-episode-' + videoID ).find('h5').html(jsonData.name);
}
我也尝试过使用each函数,但没有成功。我确信我只是在Javascript中遗漏了一些东西,但你可以帮我弄清楚。
谢谢!
函数中videoID
的作用域是全局的。每次迭代脚本时,都会更新其值。当回调被触发(异步)时,它已经循环通过,并且videoID
具有上次设置的最后一个值。
由于从API返回的JSON包含id,因此只使用它将是最简单的:
function response(jsonData) {
jQuery('li.recent-episode-' + jsonData.id ).find('h5').html(jsonData.name);
}