Basics:我有一个网页,它将几个内容div加载到一个页面,然后在用户单击"load more“链接时依次显示它们。
这里的例子:JSFiddle实例
$("#load-more").click(function(e) {
var t = $(this);
if (t.data('disabled')){
return;
}
var hiddenGroups = $('.group:not(:visible)');
if (hiddenGroups.length > 0){
hiddenGroups.first().show();
} else{
t.data('disabled', true);
}
});
我有两个基于这个例子的问题:
1)当最终的div显示时, "load more“链接应该隐藏其自身,但在我的示例中没有正确运行。
不过,我真的很想:
2)隐藏“加载更多”div,而是显示/更改功能以“隐藏项”,并在单击时按相反顺序隐藏内容div。
发布于 2014-07-28 22:03:00
我就是这样做的:
JSFIDDLE
这个想法是:
设置一个变量,指示是否正在或多或少地切换。
var load = 'more';
检查我们的装载量是多少
还有一个函数来切换方向和按钮文本,停止复制/粘贴相同的javascript。
虽然函数中只发生了两件事,但我认为随着应用程序的增长,它可能会增长--如果这不是要增长的话,那么就应该摆脱这个函数,只添加其他的代码。
完整的片段:
var load = 'more';
$("#load-more").on('click',function (e) {
// show the next hidden div.group, then disable load more once all divs have been displayed
// if we are loading more
if (load == 'more') {
// get the amount of hidden groups
var groups = $('.group:not(:visible)');
// if there are some available
if (groups.length > 0) {
// show the first
groups.first().show();
// if that was the last group then set to load less
if (groups.length == 1) {
switchLoadTo('less');
}
}
// we are loading less
} else {
// get the groups which are currently visible
var groups = $('.group:visible');
// if there is more than 1 (as we dont want to hide the initial group)
if (groups.length > 1) {
// hide the last avaiable
groups.last().hide();
// if that was the only group available, set to load more
if (groups.length == 2) {
switchLoadTo('more');
}
}
}
});
function switchLoadTo(dir) {
load = dir;
$("#load-more").html('Load ' + dir);
}
发布于 2014-07-28 22:02:02
http://jsfiddle.net/8Re3t/20/
见下面的片段。可能不是最优化的代码,但是您了解这个想法,并且可以在实现上对其进行优化。
var load = true;
$("#load-more").click(function(e) {
// show the next hidden div.group, then disable load more once all divs have been displayed
var t = $(this);
if (t.data('disabled')){
return;
}
var hiddenGroups = $('.group:not(:visible)');
if(load) {
hiddenGroups.first().show();
} else {
$('.group:visible').last().hide();
}
if (hiddenGroups.length > 1){
jQuery("#load-more").html("Load");
load = true;
} else {
jQuery("#load-more").html("Hide");
load = false;
}
});
https://stackoverflow.com/questions/25004880
复制相似问题