我有五个段落带有一些特定的类名。
<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/