将数据属性动态添加到Img标签

问题描述 投票:1回答:1

我正在向数组中的每个img标签添加“ data-index =”。它应该等于数组中的数字。例如,它将打印"<img class="gallery-item" data-index="1" src="<?php the_field('image'); ?>" alt="">,依此类推。有人可以建议如何做到这一点吗?这就是我的代码:

*更新后的代码可以反映答案

HTML

<div id="container" class="isotope" data-element="gallery-item">
    <?php 
    $idx=0;
    $args = array(
        'post_type' => 'Photos',
    );
    $_posts = new WP_Query($args);
    ?>
    <?php 
    if ( $_posts->have_posts() ) : while ( $_posts->have_posts() ) : $_posts->the_post(); ?>

    <div class="grid-item" data-filter="<?php 
        $categories = get_the_category(get_the_id());
        foreach ($categories as $category){ 
        echo $category->slug;}?>">
    <a onClick='showDialog()' data-target="#lightbox">
    <img class="gallery-item" data-index="<?php esc_attr_e( $idx ); ?>" src="<?php the_field('image'); ?>" alt="">
    </a>
    </div>
    <?php
    $idx++;
    endwhile; endif;
    ?>
</div>

我正在向数组中的每个img标签添加“ data-index =”。它应该等于数组中的数字。例如,它将打印“

javascript php arrays wordpress custom-data-attribute
1个回答
0
投票

您应该创建一个变量来存储索引(例如:$idx)并在每个循环中将其递增:

© www.soinside.com 2019 - 2024. All rights reserved.