如何使用 Jquery 截断长无序列表?
我正在使用 wordpress 显示类别列表,按字母顺序排序。我想使用 jQuery 在前 20 个链接后面附加一个“阅读更多”链接。当用户单击“阅读更多”时,其余类别会向下滑动/显示。列表的 HTML 格式如下:
<ul id="catA">
<h2>Categories</h2>
<li class="cat-item">
<a title="title" href="#">Category Name</a>
</li>
<li class="cat-item">
<a title="title" href="#">Category Name</a>
</li>
<li class="cat-item">
<a title="title" href="#">Category Name</a>
</li>
...
</ul>
我希望将 查看所有类别
添加到 20rh 类别之后的列表中,并隐藏所有内容在那之后。在我尝试编写一些代码之前,对解决此问题的最佳方法有什么想法吗?
I am using wordpress to display a list of categories, sorted alphabetically. I want to use jQuery to append a "read more" link after the first 20 links. When the user clicks "read more" the rest of the categories slide down/appear. The HTML format of the list is below:
<ul id="catA">
<h2>Categories</h2>
<li class="cat-item">
<a title="title" href="#">Category Name</a>
</li>
<li class="cat-item">
<a title="title" href="#">Category Name</a>
</li>
<li class="cat-item">
<a title="title" href="#">Category Name</a>
</li>
...
</ul>
I want the <a href="#">view all categories</a>
to be appended to the list after the 20rh category, and hiding everything after that. Before I attempt to write some code, any thoughts on the best way to go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会使用 :eq() 选择器找到第 20 个 li 元素(注意它是 < em>零索引),在其后添加“查看全部”链接,然后使用 :gt() 选择器 选择并隐藏你多余的 li 元素。您需要将一个事件处理程序附加到“查看全部”链接,以显示隐藏的 li 并自行删除。
I would find the 20th li element using the :eq() selector (noting that it is zero-indexed), add your View All link after it, then make use of the :gt() selector to select and hide your extra li elements. You would need to attach an event handler to your View All link that shows the hidden li's and removes itself.
我会这样做:
这是 jsfiddle 显示我的方法的实际应用。
我根据 @nachito 关于使用
:gt()jsfiddle代码>选择器。我还添加了一些评论来解释正在发生的事情。
I would do it like this:
Here is the jsfiddle showing my method in action.
I created an updated jsfiddle based on @nachito's recommendation on using the
:gt()
selector. I also added some comments explaining what's happening.这是最简单的解决方案,但可能有效:
点击“查看全部”后,我们会显示所有元素。
This is the simplest solution, but may work:
On click on 'view all', we show all the elements.