jquery show()和hide()

时间:2014-01-12 18:02:06

标签: jquery hide show

我有一个div:

<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并替换按钮时,但是当我第二次单击隐藏脚本时不起作用..有什么帮助?

2 个答案:

答案 0 :(得分: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");
        }
    });
});

答案 1 :(得分: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时,内容在可见和隐藏之间切换。之后,按钮上的文本被交换为更合适的文本。

相关问题