2011-06-27 268 views
1

我在我的應用程序中插入了一些顯示/隱藏按鈕。 我的問題是:當我點擊任何按鈕時總是先打開。 這就是功能:顯示/隱藏按鈕

function showHide(shID) { 
    if (document.getElementById(shID)) { 
    if (document.getElementById(shID+'-show').style.display != 'none') { 
     document.getElementById(shID+'-show').style.display = 'none'; 
     document.getElementById(shID).style.display = 'block'; 
    } 
    else { 
     document.getElementById(shID+'-show').style.display = 'inline'; 
     document.getElementById(shID).style.display = 'none'; 
    } 
    } 
} 

這是我的插入功能:

function insert($string) 
{ 
    $result = '<div id="wrap"> 

      <a href="#" id="example-show" class="showLink" onclick="showHide(\'example\');return false;">Vizualizare</a></p> 
     <div id="example" class="more"> 
      <p> '. $string .'</p> 
      <p><a href="#" id="example-hide" class="hideLink" onclick="showHide(\'example\');return false;">Ascunde</a></p> 
     </div> 
       </div>'; 
    return $result; 
} 
+0

你是不是想鏈接的榜樣秀「上單擊時,顯示DIV的榜樣」? – Giann

+0

這是PHP的底部?如果它應該添加一個PHP標記... – Ben

+1

您應該使用[jQuery](http://api.jquery.com/toggle/)! – Shef

回答

2

你總是提供相同的參數來顯示隱藏(),所以元素的ID將永遠是相同的。但ID必須是唯一的。

而不是使用ID從單擊的按鈕開始遍歷文檔。

實施例:

function showHide(btn) 
{ 
    var target; 
    if(btn.parentNode.parentNode.className=='more') 
    { 
    target=btn.parentNode.parentNode; 
    } 
    else 
    { 
    target=btn.parentNode.getElementsByTagName('div')[0]; 
    } 

    target.style.display=(target.style.display == 'block')?'none':'block'; 
    target.parentNode.getElementsByTagName('a')[0].style.display 
    =(target.style.display != 'none')?'none':'block'; 
} 

提供這裏只this(沒有引號)作爲參數來showHide()

觀看小提琴:http://jsfiddle.net/doktormolle/kZDvh/

+0

在這種情況下,使用jQuery,以便您的代碼不會變得瘋狂;) – ThiefMaster

+0

如何在這裏使用jquery? 請給我一個例子 我是jquery的新手 而且我有一個項目,我必須在明天結束它。謝謝! – alexandrina

+0

這裏沒有必要使用jQuery。如果你還沒有使用它,你不應該只爲這一功能加載它。上面的代碼沒有jQuery。 –

0

,因爲沒有顯示:沒有用於任一BTN放映或div-example,所以最初它們都將可見。然後根據if-then在你的函數中的順序,無論你首先點擊哪個按鈕,瀏覽器總是隱藏顯示按鈕並使div-example顯示:block。所以也許你需要隱藏其中一個最初由一些CSS或JS設置。

0

試試這個:

<span><div> 
<input type="button" value="Show" onclick="if (this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display != '') { this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = ''; this.value = 'Hide'; } else { this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = 'none'; this.value = 'Show'; }" style="font-size: 11px; cursor: pointer;"> 
</div> 
<div class="alt2" style="border: 0px inset; margin: 0px; padding: 6px;"> 
<div style="display: none;"> <!-- Is content default show: remove none --> 

    <!-- Content Show/Hide Here --> 

</div> 
</div></span> 
+0

歡迎來到StackOverflow!我相信這個答案在您的代碼旁邊有一些解釋可能會更好。特別是在你的'onclick'部分,因爲這樣的內聯JavaScript很難閱讀。 –

+0

@BrianJ我是sory,不理解你的問題,我的英語很糟糕。 我如果明白:因爲命令出現在目標之前,所以在閱讀時沒有困難。如果想重複按鈕,我把。 – jmsmarcelo