簡體   English   中英

使用jQuery切換.sliced文本

[英]Toggling .sliced off text with jQuery

我想切換.slice切掉前100個字符后隱藏的文本。

我有以下代碼:

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. 班級是跨度的,不是段落,但是您在段落上切換。

  2. 您不包含. 調用toggleClass 該點用於在CSS中引入類選擇器,而不是類名稱的一部分。

所以:

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

現場示例:

 $(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'); }); }); 
 .hidden { display: none; } 
 <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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM