2017-06-07 18 views
0

例如,我有這個功能。我可以使用getElementById選擇和隱藏沒有指定id的內容嗎?

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個部分具有其經由

<div id="post-<?php 
    $posttags = get_the_tags(); 
    if ($posttags) { 
     foreach($posttags as $tag) { 
      echo $tag->name . ' '; 
     } 
    } 
?>" class="col-md-4 no-pad containerhover"> 

產生的ID,目前,當我點擊一個按鈕,它隱藏或顯示後打印

的內容

我希望它隱藏/顯示我擁有的其他7個部分的內容,所以後期打印一直存在。

我認爲應該有某種方式來隱藏每個DIV的類,除非它們具有指定的ID。

+0

什麼的生成的ID是什麼樣子? – PeterMader

+0

HTML'id'屬性值應該[不包含任何空格](https://www.w3.org/TR/html5/dom.html#the-id-attribute)。 – trincot

+0

根據你的代碼, 你將有class =「post-tag1 tag2」...你不是指post-tag1 post-tag2 ... ect – fxlacroix

回答

1

首先,HTML id屬性應該是not contain any spaces,所以你需要調整你的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>

+0

你能給我一些反饋嗎?這是否回答你的問題? – trincot

相關問題