开发者

jquery show-hide based on character count

I want to hide text in a div after a certain number of characters, and limit it on a word. I found this solution: jquery limit text by length but it does not have a way to close the div back up or break on a word.

This is what I've got so far... This allows me to open and close a div. But I want it to be different in that I want it to check the text until it gets to a certain number of characters. It would then wrap a DIV from that position to the end of the text which could then be hidden with the hide() method. I have to add this to thousands of nodes. So I can't go through each one and add the show/hide span that is in this example

<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>

I found this on an answer to a different question, but I don't know how to merge the two sets of functionality:

<script type="text/javascript" charset="utf-8">
        $(开发者_如何学Cfunction(){
                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>


You can easily do something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜