单击img链接后显示图像

时间:2018-09-22 06:26:49

标签: javascript jquery wordpress

我试图在用拇指单击后以大图像显示相同颜色的相同产品的图像。它不是商店,所以我没有使用woocommerce。

我使用自定义字段colors-iglo创建了一个名为image的自定义帖子类型,以将第二个img添加为我的拇指,并且我正在使用帖子缩略图来存储/显示大图像。

循环:

<img src="<?php the_post_thumbnail(); ?>" id="currentImg">

    <ul class="colorpicker">
      <?php
        $args = array(
          'post_type'  => 'colors-iglo',
          'orderby'    => 'date',
          'order'      => 'ASC',
          'posts_per_page' => '3'

        );

        $the_query = new WP_Query( $args );
        while ( $the_query->have_posts() ) : $the_query->the_post();

        $meta = get_post_meta( $post->ID, 'images_colors', true );
      ?>

      <li id="post-<?php the_ID(); ?>" class="product-wrapper handles-wrapper col-12 col-xl-4">
        <div class="product-img">
          <?php
            echo '<img src=" '.$meta['image'].'" onclick="showImage(" '.the_post_thumbnail().' ") />';
           ?>
        </div><!-- .product-img -->
        <p class="product-name col-12 col-xl-12"><?php the_title(); ?></p>
      </li><!-- .product-wrapper -->

      <?php
        endwhile;
      ?>
      <?php wp_reset_postdata(); ?>
    </ul>

js

<script>
    jQuery(function($){

      function showImage(imgPath, imgText) {
          var curImage = document.getElementById('currentImg');

          curImage.src = imgPath;
          curImage.alt = imgText;
          curImage.title = imgText;
       }

    });
    </script>

问题,我不知道如何解决:

<img src="<?php the_post_thumbnail(); ?>" id="currentImg">未显示大图。另外,我希望它在页面加载后显示第一种颜色的大图像。

echo '<img src=" '.$meta['image'].'" onclick="showImage(" '.the_post_thumbnail().' ") />';显示的是自定义字段图像,但也显示了onclick发布缩略图。

更新 This is the current output

1 个答案:

答案 0 :(得分:0)

您需要修复代码中的流:

  1. showImage范围之外声明jQuery(function($)

  2. 在加载文档时单击第一个拇指即可触发。

  3. 在您的PHP脚本中为showImage调用添加第二个参数。

JavaScript

function showImage(imgPath, imgText) {
   var curImage = document.getElementById('currentImg');
   curImage.src = imgPath;
   curImage.alt = imgText;
   curImage.title = imgText;
}

jQuery(function($){
    // trigger click on 1st image
    jQuery('.product-img').first().find('img').click();
});

PHP

替换

 echo '<img src=" '.$meta['image'].'" onclick="showImage(" '.the_post_thumbnail().' ") />';

使用

 echo '<img src=" '.$meta['image'].'" onclick="showImage(\' '.the_post_thumbnail().'\', \'\')"/>';
相关问题