例如,我有此功能。
function showprintdiv() {
var x = document.getElementById('post-Print ');
if (!x.style.display || x.style.display == 'block') {
x.style.display = 'none';
} else {
x.style.display = 'block';
}
我具有7次功能,其中8个部分具有通过
生成的ID<div id="post-<?php
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name . ' ';
}
}
?>" class="col-md-4 no-pad containerhover">
当前我单击按钮时,它会隐藏或显示后印刷的内容
我希望它隐藏/显示我所拥有的其他7个部分的内容,所以后印刷一直存在。
我认为应该有某种方法可以用类别隐藏每个Div,除非它们具有指定的ID。
首先,HTML id
属性不应包含任何空间,因此您需要为此适应PHP代码。有必要在以下内容起作用之前:
专注于您的问题:如果要到达所有post-
元素,一个特定的 post-Print
,然后将querySelectorAll
与智能CSS选择器[id^=post-]:not(#post-Print)
一起使用。
这是一个演示:
function showprintdiv() {
// Iterate over all elements that have an id that starts with "post-",
// except the one you want to keep visible:
var elems = document.querySelectorAll('[id^=post-]:not(#post-Print)');
Array.from(elems, function (x) {
if (x.id == 'post-Print') return; // don't touch this one.
x.style.display = (!x.style.display || x.style.display == 'block')
? 'none' : 'block';
});
}
// Demo: toggle visibility every half second:
setInterval(showprintdiv, 500);
<div id="post-Print" class="col-md-4 no-pad containerhover">post-Print</div>
<div id="post-1" class="col-md-4 no-pad containerhover">post-1</div>
<div id="post-2" class="col-md-4 no-pad containerhover">post-2</div>
<div id="post-3" class="col-md-4 no-pad containerhover">post-3</div>