如何隐藏列表中的元素并添加“显示更多”功能? [英] How can I hide elements in my list and add a 'show more' feature?

查看:91
本文介绍了如何隐藏列表中的元素并添加“显示更多”功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用javascript来构建结果列表。我有一个for循环遍历一些数据并创建一个mydata div,并将其添加到结果div。让我们假装它看起来像这样:

 < div id =results> 
< div class =mydata> data 1< / div>
< div class =mydata> data 2< / div>
...
< div class =mydata> data 20< / div>
< / div>

我想做的是一次只显示5个结果并且如果用户希望看到更多,他们可以点击显示下一个显示更多按钮(或类似的东西)。任何想法?



为了澄清,每次用户点击显示更多时,我想取消隐藏接下来的5个元素,而不是所有剩余的元素。

解决方案

您可以使用 gt / code>和 lt()选择器以及:visible b
$ b

以下将显示点击后的5个结果,并在所有项目都可见后删除链接。

  $('。mydata:gt(4)')。hide()。last()。after(
$('< a />').attr('href' #')。text('Show more')。click(function(){
var a = this;
$('。mydata:not(:visible):lt(5)')。 fadeIn(function(){
if($('。mydata:not(:visible)')。length == 0)$(a).remove();
}); return false;
})
);

工作示例: http://jsfiddle.net/niklasvh/nTv7D/



无论其他人在这里推荐什么,我都使用CSS隐藏元素,但在JS中做它,因为如果用户已禁用JS,并使用CSS隐藏元素,他不会让他们可见。然而,如果他有JS禁用,他们永远不会被隐藏,也不会显示的那个按钮等,所以它有一个完整的noscript回退到位+搜索引擎不喜欢隐藏的内容(但他们不会知道它的隐藏,如果你做DOM负载)。


I'm using javascript to build a list of results. I have a for-loop that iterates over some data and creates a mydata div, and adds that to the results div. Let's pretend it looks something like this:

<div id="results">
    <div class="mydata">data 1</div>
    <div class="mydata">data 2</div>
    ...
    <div class="mydata">data 20</div>
</div>

What I want to do is only display 5 results at a time, and should the user wish to see more, they can click a show next 5 or show more button (or something similar). Any ideas?

Just to clarify, every time the user clicks "show more" I want to 'unhide' the next 5 elements, not ALL the remaining elements. So each click reveals more elements until all are displayed.

解决方案

You can use the gt() and lt() selectors along with :visible pretty well here.

The following will show the next 5 results on clicking and removes the link once all items are visible.

$('.mydata:gt(4)').hide().last().after(
    $('<a />').attr('href','#').text('Show more').click(function(){
        var a = this;
        $('.mydata:not(:visible):lt(5)').fadeIn(function(){
         if ($('.mydata:not(:visible)').length == 0) $(a).remove();   
        }); return false;
    })
);

working example: http://jsfiddle.net/niklasvh/nTv7D/

Regardless of what other people are suggesting here, I would not hide the elements using CSS, but do it in JS instead, because if a user has JS disabled and you hide the elements using CSS, he won't get them visible. However, if he has JS disabled, they will never get hidden, nor will that button appear etc, so it has a full noscript fallback in place + search engines don't like hidden content (but they won't know its hidden if you do it on DOM load).

这篇关于如何隐藏列表中的元素并添加“显示更多”功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆