2011-07-14 18 views
0

我想隱藏文本在一定數量的字符後,並限制在一個字。我發現這個解決方案:jquery limit text by length,但它沒有辦法關閉備份或打破一個字。基於字符數的jQuery顯示隱藏

這是我到目前爲止...這讓我打開和關閉一個div。但我希望它與衆不同,因爲我希望它能檢查文字,直到達到一定數量的字符。然後它會將DIV從該位置包裝到文本的末尾,然後可以使用hide()方法隱藏該文本。我必須將其添加到數千個節點中。所以我不能去通過每一個,並添加顯示/隱藏跨度在這個例子中

<html> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/javascript"> 
    function showStuff(id) { 
     document.getElementById(id).style.display = 'block'; 
    } 
    function hideStuff(id) { 
     document.getElementById(id).style.display = 'none'; 
    } 
</script> 

<style type="text/css"> 
    span.read-more { cursor: pointer; color: red; } 
    span.more { display: none; } 
</style> 
</head> 
<body> 

<p><a href="#" onclick="showStuff('answer1'); return false;">What price are your apples?</a><br> 
<span id="answer1" style="display: none;">Our apples are 30 pence each. If you buy 10 or more we can sell them at a discounted bulk rate of 25 pence each. 
<a href="#" onclick="hideStuff('answer1'); return false;">Close</a><br> 
</span></p> 

</body> 
</html> 

我發現這個在回答不同的問題,但我不知道如何合併兩個功能集:

<script type="text/javascript" charset="utf-8"> 
     $(function(){ 
       var $elem = $('p');    // The element or elements with the text to hide 
       var $limit = 10;    // The number of characters to show 
       var $str = $elem.html();  // Getting the text 
       var $strtemp = $str.substr(0,$limit); // Get the visible part of the string 
       $str = $strtemp + '<span class="hide">' + $str.substr($limit,$str.length) + '</span>'; // Recompose the string with the span tag wrapped around the hidden part of it 
       $elem.html($str);    // Write the string to the DOM 
     }) 
    </script> 
+0

你能提供更多的背景?也許一些HTML和代碼 – mikeycgto

+0

我增加了更多的我原來的問題...感謝您的期待... – Kappaluppa

回答

2

您可以輕鬆地做這樣的事情:

if ($(".yourelement").html().length > 50) { // if count is greater than 50 
    $(".yourelement").slideUp("slow"); 
}