2017-09-26 25 views
0

我實現jQuery顯示/隱藏報價鏈接時遇到了一個有趣的障礙,因爲當引號結束煩人地長。所以,如果報價太長,請使用show link將其隱藏起來。jquery隱藏長引號與顯示更多/更少

一個簡單的「每個」檢查類報價是容易的。問題是,引號可以包含引號,並且會打破它,因爲它會嘗試在每個引用上執行它,而不是頂部引用。

下面的代碼我現在所擁有的:

// hide long quotes 
var showChar = 350; 
var ellipsestext = "..."; 
var moretext = "Click for more"; 
var lesstext = "Click for less"; 
$('.comment_quote').each(function() 
{ 
    var content = $(this).html(); 

    if(content.length > showChar) 
    { 
     var c = content.substr(0, showChar); 
     var h = content.substr(showChar-1, content.length - showChar); 

     var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>'; 

     $(this).html(html); 
    } 

}); 

$(".morelink").click(function(){ 
    if($(this).hasClass("less")) { 
     $(this).removeClass("less"); 
     $(this).html(moretext); 
    } else { 
     $(this).addClass("less"); 
     $(this).html(lesstext); 
    } 
    $(this).parent().prev().toggle(); 
    $(this).prev().toggle(); 
    return false; 
}); 

我不能想到了解決辦法,將兩個環路通過頁面來接他們,並挑選最頂​​端的報價連稱「comment_quote」級每一次。

+0

是你所談論的頂部嗎?關於文本又是什麼可以打破它呢?他們是否包含HTML或其他? – Harry

+0

你可以創建一個小提琴或添加HTML和CSS來創建證據嗎? – gaetanoM

+0

如果您控制引號,只需刪除引號並使用jQuery添加引號即可。如果你不控制引號,那麼你可以在你的問題發生之前將它們移除varc = content.replace(/'/ g,'').substr(0,showChar);'然後在手動添加它們時你完成了你的操縱 –

回答

0

我覺得這個例子可以幫助你:)

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" 
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
    <title>Document</title> 
    <script type="text/javascript" src="jquery-3.2.1.min.js" ></script> 
</head> 
<div id="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
    Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div> 

<body> 
<script> 
    $(function() { 
      var text = $('#text').text(); 
      var nw=[]; 
      var leng = text.length; 
      var result=""; 
      if(leng>50){ 
       nw[0] = text.substr(0, 50); 
       nw[1] = " <a href='#' id='btn'>more..</a>"; 
       nw[2] = text.substr(50); 
       result = nw[0] + nw[1]; 
       $('#text').html(result); 
      } 
     $('#btn').click(function() { 
      result = nw[0] + nw[2]; 
      $('#text').html(result); 
     }); 


    }); 
</script> 
</body> 
</html>