我想在某一天找到一个解决方案,但无法找到方法。我在一个按钮上有一个功能,隐藏每个没有聚酯类的div。
然后我有另一个按钮想要隐藏其他所有内容,但我不想隐藏已经显示的内容(在这种情况下为聚酯),活动类是什么。
let polyval = document.getElementById('poly').getAttribute('value');
let lightval = document.getElementById('light').getAttribute('value');
function showpoly(e){
const poly = document.getElementById('poly');
const nopoly = document.querySelectorAll("div.webbing:not(.polyester)");
const len = nopoly.length;
if(polyval < 1) {
polyval++;
for(i = 0; i < len; i++){
nopoly[i].classList.add('active');
}
}else {
polyval--;
for(i = 0; i < len; i++){
nopoly[i].classList.remove('active');
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>What webbing will you buy next ?</title>
<link rel="stylesheet" href="main.css">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
</head>
<body>
<h1>WHAT WEBBING WILL I BUY NEXT ?</h1>
<div class="container">
<div class="row">
<div class="col s12">
<a onclick="showpoly();" class="waves-effect waves-light btn-large">Polyester</a>
<a onclick="showlight();" class="waves-effect waves-light btn-large">Light</a>
</div>
</div>
<div class="row">
<div value="0" class="col s2 webbing polyamid">
Polyamid
</div>
<div value="0" id="poly" class="col s2 webbing polyester">
Polyester
</div>
<div value="0" class="col s2 webbing nylon">
Nylon
</div>
<div value="0" class="col s2 webbing tubular">
Tubular
</div>
<div value="0" class="col s2 webbing heavy">
Heavy
</div>
<div value="0" id="light" class="col s2 webbing light">
Light
</div>
<div value="0" class="col s2 webbing polyamid">
Polyamid
</div>
<div value="0" id="poly" class="col s2 webbing polyester">
Polyester
</div>
<div value="0" class="col s2 webbing nylon">
Nylon
</div>
<div value="0" class="col s2 webbing tubular">
Tubular
</div>
<div value="0" class="col s2 webbing heavy">
Heavy
</div>
<div value="0" id="light" class="col s2 webbing light">
Light
</div>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
答案 0 :(得分:0)
你可以使用jQuery的hasClass();用于检查Element是否具有类的函数。
在你的情况下会是这样的
if ($(element).hasClass('polyester')) {
// Do Nothing!
}
else {
//Hide That Div!
}
我没有使用带有条件的not(!)只是为了让你变得简单,否则你可以使用!没有条件翻转条件所以它将是
if (!$(element).hasClass('polyester')) {
// Hide code
}
请用您想要的元素替换(元素)。并在按钮的Click事件中使用它....
由于时间不够,抱歉无法为您创建确切的代码! : - )
答案 1 :(得分:0)
在香草js:
function hideWithoutClass(nodeList, className) {
nodeList.forEach( v => {
if (!v.classList.contains(className)) v.style.visibility = 'hidden'
})
}