简体   繁体   English

限制数量 <li> 中的元素 <ol> 和 <ul>

[英]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? 是否可以通过html直接限制olulli元素的数量?

If I want to do it with javascript or jquery, how would I do it? 如果我想用javascript或jquery来做,我该怎么做?

You can do it with CSS 3, if you finally want to hide them. 你可以使用CSS 3,如果你最终想要隐藏它们。

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

jQuery provides selectors that can simplify this process. jQuery提供了可以简化此过程的选择器。 For example, if you want to remove li elements at an index greater than 2: 例如,如果要删除索引大于2的li元素:

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

Or you can simply hide via css if you like: 或者,如果你愿意,你可以简单地通过CSS隐藏:

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

Here's an example jsfiddle . 这是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. 我的解决方案只是隐藏索引超过某个定义的最大值的元素 - 但您可以轻松地使用remove() 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. 据我所知,没有办法在HTML中本地执行此操作。 But it's very easy to do so in JS or jQuery. 但是在JS或jQuery中这样做很容易。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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