javascript - jQuery 显示具有特定类的部分以及相同类或子类的按钮

标签 javascript jquery

我有五个段落带有一些特定的类名。

<p class ='biology_biotech'>1 Biology Biotech</p>
<p class ='biology'>2 Biology</p>
<p class ='biotech'>3 Biotech</p>
<p class ='physics'>4 Physics</p>
<p class ='chemistry'>5 Chemistry</p>

为了切换它们的可见性,我有几个具有相同或相似类的按钮。

<input type = 'button' class ='physics' value = 'physics'/>
<input type = 'button' class ='chemistry' value = 'chemistry'/>
<input type = 'button' class ='biology' value = 'biology'/>
<input type = 'button' class ='biotech' value = 'biotech'/>

如果我单击具有特定类的按钮,例如“biology”,我应该能够看到所有类名中包含字符串“biology”的段落,即第 1 段和第 2 段。 同样,如果我单击具有生物技术类的按钮,则第 1 段和第 3 段。等等。

但是我无法得到想要的结果,我使用了 indexOf 和 inArray。以下是我的代码。

$(function () {
    $("input").click(function() {
    var inpClass = $(this).attr("class");       
    var collection = $("p");
    collection.each(function() {
    var listClass = $(this).attr("class");
    var listItems = listClass.split("_");
    //console.log(inpClass);
    //console.log(listClass);
    //console.log(listItems);
    if(jQuery.inArray(inpClass, listItems) !== -1){
    collection.hide();
    $("."+listClass).fadeIn();
    }
    });
    });

});

这是一个JSbin为了这。 谢谢

最佳答案

改变

$("."+listClass).fadeIn();

成为

$('[class*='+listClass+']').fadeIn();

关于javascript - jQuery 显示具有特定类的部分以及相同类或子类的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48611237/

相关文章:

javascript - jQuery val() 无法在 Aloha Editor 的动态 <select> 上正常工作

jQuery 倒计时插件无法与 Ace Editor 一起使用

javascript - 无法分配元素的最后位置坐标

javascript - 带有图像的自定义文本区域

javascript - Jquery HTML 选择标签附加重复本身

javascript - tinyMCE 在 getContent 上将 <i> 变成 <em>

javascript - 组合JQuery变量+模板变量

jquery - 为什么 jquery/css 需要 'px' 作为 top 属性,而不是 width 或 height 属性?

javascript - Jquery.Change 不起作用

jQuery下拉菜单向下和向上滑动