简体   繁体   中英

Limit number of <li> elements in <ol> and <ul>

Is it possible to limit number of li elements in ol and ul directly through html?

If I want to do it with javascript or jquery, how would I do it?

You can do it with CSS 3, if you finally want to hide them.

li:nth-of-type(1n+15) {
    display: none;
} 

jQuery provides selectors that can simplify this process. For example, if you want to remove li elements at an index greater than 2:

$('#myList li:gt(2)').remove();

Or you can simply hide via css if you like:

#myList li:nth-of-type(1n+4) {
  display: none;
}

Here's an example jsfiddle .

您可以使用class和li元素隐藏类下的li(这不会隐藏页面上的所有li,而是隐藏指定类下的li)。

.class li:nth-of-type(1n+4) { display: none; };

Here's something I knocked up quickly. My solution is just to hide the elements whose index exceeds some defined maximum - but you can use remove() just as easily. Take a look:

 var max = 2; $('ul, ol').each(function(){ $(this).find('li').each(function(index){ if(index >= max) $(this).hide() }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> <ol> <li>1</li> <li>2</li> <li>3</li> </ol> 

To the best of my knowledge, there's no way to do this natively in HTML. But it's very easy to do so in JS or jQuery.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM