根据按钮的ID数据隐藏类元素

问题描述

HTML

<a class="us-btn-style_6" id="post-102" href="#">Real Estate</span></a>
<article class="w-grid-item post-102" data-id="102"></article>

jQuery函数

$('.w-grid-item').hide();
var class1 = ".";
var post_class = "";
$('.us-btn-style_6').click(function(){
    post_class = $(this).data('id')
    post_class = class1 + post_class
    $(post_class).show();
});

有7个按钮和7个对应的<articles>。按钮的ID文章class具有相同的数据。当单击按钮<article>时,需要简单地显示发生的情况。在jQuery中,我尝试获取ID数据以显示相应的类。怎么了?

解决方法

使用.data方法时,应该有一个对应的data-前缀属性,在这种情况下为data-id

<a class="us-btn-style_6" data-id="post-102" href="#">Real Estate</a>

这是一个有效的代码段:

$('.w-grid-item').hide();
var class1 = ".";
var post_class = "";
$('.us-btn-style_6').click(function(){
    post_class = $(this).data('id')
    post_class = class1 + post_class
    $(post_class).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="us-btn-style_6" data-id="post-102" href="#">Real Estate</a>
<article class="w-grid-item post-102">
Test
</article>

,

您将data-id放在错误的元素中。它需要在您单击的项目上,而不是要显示的元素上。

我会像这样清理它:

$("[data-toggles]").on("click",function (evt) {
  evt.preventDefault();
  var selector = $(this).data("toggles");
  $(".post").hide();
  $(selector).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="us-btn-style_6" data-toggles=".post-102" href="#">Real Estate</span></a>
<a class="us-btn-style_6" data-toggles=".post-103" href="#">Foo Estate</span></a>


<article class="w-grid-item post post-102">X</article>
<article class="w-grid-item post post-103">Y1</article>
<article class="w-grid-item post post-103">Y2</article>