【问题标题】:jquery show() and hide()jquery show() 和 hide()
【发布时间】:2014-01-12 18:02:06
【问题描述】:

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

【问题讨论】:

    标签: jquery hide show


    【解决方案1】:

    我会考虑重写一下:

    $('#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 时,会在可见和隐藏之间切换。之后,按钮上的文本被交换为更合适的文本。

    【讨论】:

    • 哇!!!有用!!非常感谢你..也许我需要学习一些javascript! :)
    • 我看到了一个错误...当内容被隐藏时,按钮的文本不会改变..它仍然是“显示较少的新闻”...我替换了按钮文本,并添加了一个 if控制文本并以防万一进行更改..它可以工作...
    【解决方案2】:

    问题是在您将事件绑定到的位置不再存在该按钮。因此,您可以创建一个新按钮并向其添加事件处理程序。或更改输入文本并拥有 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");
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-03-08
      • 1970-01-01
      • 2013-02-25
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      相关资源
      最近更新 更多