2014-01-12 142 views
0

我有一個div:jQuery的顯示()和隱藏()

<div class="showHide"> 
    //content 
</div> 

和一個按鈕

<button id="event" class="show" type="button">Show more news</button> 

CSS是:

.showHide { 
    display: none; 
} 

這裏的jQuery:

function show() { 
    $(".show").click(function(){ 
    $(".hideShow").show(500,'linear'); 
    $(".show").replaceWith('<button id="event" class="hide" type="button">Show less news</button>'); 
}); 
} 
function hide() { 
    $(".hide").click(function(){ 
    $(".hideShow").hide(500, 'linear'); 
    $(".hide").replaceWith('<button id="event" class="show" type="button">Show more news</button>'); 
}); 
} 

$(document).ready(function() { 
    show(); 
    hide(); 
}); 

當我第一次點擊腳本顯示div並替換按鈕,但當我第二次點擊隱藏腳本不起作用..任何幫助?

回答

0

我會考慮重寫了一點:

$('#event').on('click', function() { 
    // Using toggle to switch between hidden/shown 
    $('.showHide').toggle(500); 

    // Replace text on button 
    var buttonText = ($('.showHide').is(":visible") == true) ? "Show less news" : "Show more news"; 
    $('#event').text(buttonText); 
}); 

基本上我註冊按鈕點擊事件。當它點擊與內容切換可見和隱藏的div。之後,按鈕上的文字被交換爲更適合的文字。

+0

wooow!有用!!非常感謝你..可能我需要學習一些JavaScript! :) –

+0

我看到一個錯誤...當內容被隱藏時,按鈕的文本不會改變..它仍然是「顯示較少的消息」...我替換了按鈕文本放置一個if如果控制文本並更改它在case..it工程... –

0

問題在於,按鈕不再存在於您將事件綁定到的地方。所以你可以創建一個新的按鈕並添加一個事件處理程序。或改變輸入文字,並有1個處理,如:

$(function(){ // Document ready 
    $(".showhidebtn").click(function(){ 
     $(".hideShow").toggle(500, 'linear'); 
     if($(".hideShow").is(":visible")) { 
      $(this).val("Hide element"); // Don't know if you need to use `val()` or `html()`. 
     } else { 
      $(this).val("Show element"); 
     } 
    }); 
}); 
0

有以下腳本

function show_div(){ 

    $(".showHide").show(500,'linear'); 
    $(".show").replaceWith('<button id="event" class="hide" onclick="hide_div()" type="button">Show less news</button>'); 

} 
function hide_div(){ 

    $(".showHide").hide(500, 'linear'); 
    $(".hide").replaceWith('<button id="event" class="show" onclick="show_div()" type="button">Show more news</button>'); 

} 

和下面的HTML

<div class="showHide"> 
    //content adsfasdf 
</div> 
<button id="event" class="show" onclick="show_div()" type="button">Show more news</button> 
+0

100%工作在我的系統上測試 – sanjeev