使用jQuery切换文本

时间:2015-08-03 15:22:57

标签: javascript jquery

我想切换前{100}个.slice切片后隐藏的文字。

我有以下代码:

html的

  <div class="col-sm-12">
    <p class="pdp-product-description">This has more than 100 characters and it is showing that it is sliced after the 100th</p>
    <a href="#"><span class="view-details">View Details</span></a>
  </div>

的.js

$(function() {
    var hiddenDescription = $('p.pdp-product-description');

    hiddenDescription.each(function(){
        var t = $(this).text();
        if(t.length < 100) return;
        $(this).html(
            t.slice(0,100)+'<span>... </span>'+
            '<span class="hidden">'+ t.slice(100,t.length)+'</span>'
        );
    });

    $('.view-details').click(function() {
      $('.pdp-product-description').toggleClass('.hidden');
    });
});

目前的设置似乎没有用,有什么想法吗?

1 个答案:

答案 0 :(得分:2)

两个问题:

  1. 课程是跨越的,而不是段落,但是你要在段落上翻转它。

  2. 在致电.时,您不会包含toggleClass。该点用于在CSS中引入类选择器,它不属于该类的名称。

  3. 所以:

    $('.pdp-product-description span').toggleClass('hidden');
    // ------------------------^^^^^----------------^
    

    直播示例:

    &#13;
    &#13;
    $(function() {
      var hiddenDescription = $('p.pdp-product-description');
    
      hiddenDescription.each(function() {
        var t = $(this).text();
        if (t.length < 100) return;
        $(this).html(
          t.slice(0, 100) + '<span>... </span>' +
          '<span class="hidden">' + t.slice(100, t.length) + '</span>'
        );
      });
    
      $('.view-details').click(function() {
        $('.pdp-product-description span').toggleClass('hidden');
      });
    });
    &#13;
    .hidden {
      display: none;
    }
    &#13;
    <div class="col-sm-12">
      <p class="pdp-product-description">This has more than 100 characters and it is showing that it is sliced after the 100th - This has more than 100 characters and it is showing that it is sliced after the 100th</p>
      <a href="#"><span class="view-details">View Details</span></a>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    &#13;
    &#13;
    &#13;