character limit jquery
Hello Im looking for a function that will allow me limit number of characters in li ta开发者_如何学Pythong.
Tried to do it that way:
$('li.latestnewsfooterCol').limit('5');
but this dont seem to work.
Can anyone help me please?
thank you in advance.
Part 1: Limiting number of characters
This will go through each selected li
and reduce the contents to 5 character using the .slice()
method.
Slice extracts up to, but not including the end slice.
$('li.latestnewsfooterCol').each(function() {
var $this = $(this);
$this.text( $this.text().slice(0,5) );
});
jsFiddle example
To make it into a function:
var maxNum = function($elie, num) {
var $this;
$elie.each(function() {
$this = $(this);
$this.text( $this.text().slice(0,num) );
});
}
jsFiddle example
Call the above with a jQuery object like, limit($('li.latestnewsfooterCol'), 5);
I use .each()
in both cases in case you have more than one element selected.
Part 2: Limiting words
Word count are a little more complicated. Take a look here. Fortunately it's much compacter on jQuery:
var maxNum = function($elie, num) {
var $this;
$elie.each(function() {
$this = $(this);
$this.text( $this.text().split(/\s+/).slice(0,num).join(" ") );
});
}
$(function() {
maxNum($('li.latestnewsfooterCol'),5);
});
jsFiddle example
First the text is split into an array by whitespace,$this.text().split(/\t+/)
. Then the array is sliced to the right length and rejoined with spaces, .slice(0,num).join(" ")
Note that this might replace tabs or line breaks with spaces.
As a note, consider that this will be only available to users with Javascript enabled.
Can you please be more specific? Do you want to have something like
...
<li>A very long list item</li>
...
<script type="text/javascript">
function limit(no_of_chars) {
}
limit(5);
</script>
to output
A ver
?
精彩评论