2014-11-17 239 views
0
<div class="row"> 
    <div class="large-24 columns row2 darkgreybg" id="ricontainer"> 
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> 
    </div> 
</div> 

    $(function() { 
    $("#ributton").click(function() { 
     // Hide it but only if not hidden - hide 
     $('#ricontainer:visible').hide(); 

     // Later in the script - Show it but only If it's not visible. 
     $('#ricontainer:hidden').show(); 
    }); 
    }); 

不知道爲什麼這不起作用,有什麼想法?我只是想要它,以便我有一個容器,如果可見,單擊按鈕時它將隱藏它。或者,如果它已經隱藏,點擊按鈕時會顯示它。Jquery顯示/隱藏按鈕不工作

在此先感謝。

+2

這個代碼是隱藏和顯示。條件在哪裏? – vaso123

回答

1

您可以使用.toggle()代替:

$(function() { 
    $("#ributton").click(function() { 
     $('#ricontainer').toggle(); // toggles between show/hide 
    }); 
    }); 
0

按照宰的建議,你可以使用.toggle(),但我總是覺得流淚切換結束。

$(function() { 
    $("#ributton").click(function() { 

     if($('#ricontainer').is(':visible')) 
     { 
      // Hide it but only if not hidden - hide 
      $('#ricontainer').hide(); 
     } 
     else 
     { 
      $('#ricontainer').show(); 
     } 
    }); 
    }); 

你也或許應該使用「上」,而不是「點擊」,因爲我相信這是推薦的方法,因爲jQuery的1.7版本:

$('#ributton').on('click', function(){}); 
+0

_但我總是發現切換結束淚水_.....有趣...';)'。 – Jai

+0

問題在於,在某些情況下,您最終會創建一個場景,其中當有多個字段控制「切換」字段的可見性時,切換可以反轉 – Rob

0

你的代碼將始終顯示按鈕,這是爲什麼:

按鈕最初是隱藏的:

$('#ricontainer:visible').hide(); // nothing happens, button not selected 
            // because the selector matches nothing 

$('#ricontainer:hidden').show(); // hidden button found and shown, all good 

按鈕initally所示:

$('#ricontainer:visible').hide(); // selector matched, button found 
            // now hiding the button 

$('#ricontainer:hidden').show(); // button hidden from the previous line is found 
            // so the selector matched and is now showing the button 
            // and that's the PROBLEM 

其他答案已經提示如何解決它的方法,這只是告訴你爲什麼它不像你期望的那樣工作。因此,要麼在開始時獲取按鈕的狀態,要麼使用if/else來更改其狀態,或者直接切換它。

0

,您可以用JavaScript做到這一點,如:

... 
<div class="large-24 columns row2 darkgreybg" id="ricontainer" onclick="controlButton()"> 
... 

function controlButton() { 
     var div = document.getElementById("ricontainer"); 
     if (div.style.display === "none") { 
     div.style.display = "block"; 
     } else { 
     div.style.display = "none"; 
     } 
}