【问题标题】:toggle text and classes切换文本和类
【发布时间】:2014-04-23 11:21:14
【问题描述】:

嗨,我正在寻找在点击时切换某些文本和类的最佳方法。 我也会改变背景(稍后再做)

我有一个横幅,点击时我需要在 p 上切换一些文本和一个类(隐藏和显示)

我的大致思路如下(我知道最后两行js行不通)

实现这一目标的最佳方法是什么

<div class="banner">
     <div class="content-holder">
     <h2>xxxx</h2>
     <p>xxxxxx</p>
     <p class="hidden">xxxx</p>
     <button type="button" class="tell-more">Tell me more</button>
 </div>

$(".tell-more").on("click",function(){
    $(this).html($(this).html() == 'Tell me more' ? 'close' : 'Tell me more');
    $(".banner p.hidden").removeClass("hidden").addClass("show");
    $(".banner p.show").removeClass("show").addClass("hidden");
})

刚刚做了小提琴 http://jsfiddle.net/T3G42/

【问题讨论】:

    标签: jquery toggle show-hide


    【解决方案1】:

    您可以设置特定的类,例如。 more 获取更多文本段落,然后使用 toggle 切换其可见性。

    代码:

    $(".tell-more").on("click",function(){
        $(this).html($(this).html() == 'Tell me more' ? 'close' : 'Tell me more');
        $(".banner p.more").toggle();
    })
    

    演示:http://jsfiddle.net/BcJLR/

    【讨论】:

      【解决方案2】:

      试试.toggle()

      $(".tell-more").on("click",function(){
          $('h2').toggle();
          $('p.hidden').toggle();
      })
      

      【讨论】:

        【解决方案3】:

        试试

        $(".tell-more").on("click", function () {
            $(this).html(function(i,html){
                return html == 'Tell me more' ? 'close' : 'Tell me more'
            });
            $(this).prev().toggleClass("hidden show");
        })
        

        演示:Fiddle

        【讨论】:

        • 甚至 text() 方法会更好
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-10
        • 1970-01-01
        • 1970-01-01
        • 2011-06-03
        相关资源
        最近更新 更多