基于单选选择隐藏类



我正试图根据名称隐藏一个类(例如"hiddenA"(,我以前使用过ID,但我想隐藏多个类,因此ID不再是一个选项。这就是我目前拥有的:

function onChangePackage() {
const nodes = document.getElementsByClassName('Package');
var selectedValue;
// Get selected radio
for (var i = 0, length = nodes.length; i < length; i++) {
if (nodes[i].checked) {
selectedValue = nodes[i].value;
break;
}
}
// Showing all nodes first
const nodePostFix = ['A', 'B', 'C'];
nodePostFix.forEach(node => {
const currentElement = elementsToHide.item(i);
if (currentElement.hasClass('hidden' + selectedValue)) {
currentElement.style.display = 'none';
} else {
currentElement.style.display = 'block';
}
});
}

我觉得我的代码过于复杂了,因为肯定有一种更简单的方法。

请在此处尝试此代码。您只需将按钮更改为单选按钮即可。也可以使用jquery。我想这就是你想要的。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1, #p2").toggle();
});
});
</script>
</head>
<body>
<button>Hide / Show</button>
<p id="p1">I have a class of p1</p>
<p id="p2"s>I have a class of p2</p>
<p id="p1">I have a class of p1</p>
</body>
</html>

最新更新