【问题标题】:How to target a single div in a loop with jQuery?如何使用 jQuery 在循环中定位单个 div?
【发布时间】:2020-10-14 23:56:08
【问题描述】:

我有这个循环显示来自 WordPress 博客的帖子数据 -

<?php foreach ( $product_posts as $post ) : setup_postdata( $post ); ?>
<div class="card-container">
    <div class="card-image">
        <figure>
            <a href="<?php the_permalink();?>"><?php the_post_thumbnail(); ?></a>
        </figure>
    </div>
    <div class="gallery-card-text">
        <h2><a href="<?php the_permalink();?>"><?php the_title(); ?></a></h2>
        <p><?php the_excerpt() ?></p>
    </div>
</div>
<?php endforeach; wp_reset_postdata(); ?>

使用这个 jQuery 函数 -

$(".card-container").mouseenter(function () {
  $(".gallery-card-text").show();
  $(".card-image").hide();
});

它针对循环中的所有内容,因此如果您将鼠标悬停在 1 个帖子上,它会隐藏所有帖子上的图像。我想在鼠标输入时单独显示/隐藏循环中的每个 div。

我该怎么做?

【问题讨论】:

  • 为什么还要使用 JavaScript?

标签: php jquery wordpress loops


【解决方案1】:

选择您悬停的元素中的元素。

$(".card-container").mouseenter(function () {
  var card = $(this);
  card.find(".gallery-card-text").show();
  car.find(".card-image").hide();
});

但既然简单的 CSS 可以做到,为什么还要使用 JavaScript 呢?

.card-container .gallery-card-text { display: none;} 
.card-container:hover .gallery-card-text { display: block;} 
.card-container .card-image { display: block;}
.card-container:hover .card-image { display: none;}

【讨论】:

    【解决方案2】:

    您需要指定要显示哪个.gallery-card-text,要隐藏哪个.card-image

    在使用 jQuery 的事件时,this 绑定到您设置触发器的元素,您可以使用该元素作为“范围”来确定要隐藏哪些元素

     $(".card-container").mouseenter(function () {
        var $this = $(this); // this = current .card-container
        
        // use .find() to get the elements within $this
        $this.find(".gallery-card-text").show();
        $this.find(".card-image").hide();
      });
    

    ES6

    $(".card-container")
        .mouseenter((event) => {
             // event.currentTarget = current .card-container
            let $this = $(event.currentTarget);
    
            // use .find() to get the elements within $this
            $this.find(".gallery-card-text").show();
            $this.find(".card-image").hide();
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      • 2017-01-21
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多