Jquery

Hi I am looking for a function that will allow me to limit the number of characters in the li tag.

Tried to do this:

$('li.latestnewsfooterCol').limit('5');

but this does not seem to work.

Can anybody help me?

thank you in advance.

+3
source share
2 answers

Part 1: character limit


This will go through each selected one liand reduce the content to 5 characters using . .slice()

Clippings of fragments before, but not including the final slice.

$('li.latestnewsfooterCol').each(function() {
    var $this = $(this);
    $this.text( $this.text().slice(0,5) );
});

JsFiddle example


To turn 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 above using jQuery object e.g. limit($('li.latestnewsfooterCol'), 5);

I use .each()in both cases if you have selected more than one item.


Part 2: Limit Words


. . , compacter 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


, $this.text().split(/\t+/). , .slice(0,num).join(" ") , .


, Javascript.


+8

? -

...
<li>A very long list item</li>
...
<script type="text/javascript">
    function limit(no_of_chars) {

    }
    limit(5);
</script>

A ver

?

+1

Source: https://habr.com/ru/post/1768748/


All Articles