我想有4-8个“隐藏”的div在一个页面上。然后还有两个按钮,一个“加号”和一个“删除”。当我点击“加号”按钮时,它会显示第一个div,如果我再次点击“加号”按钮,它会显示div nr 2。如果我使用"remove“,它会删除这个div。
我必须使用条件语句吗?或者有什么简单的解决方案吗?
$(document).ready(function() {
$('#show').click(function () {
$("#hiddencontent").fadeIn("slow");
});
});
发布于 2012-11-01 04:26:18
ID
是独一无二的,您不能重复使用它们,请将id="hiddencontent"
更改为class="hiddencontent"
,然后遵循下面的说明。
$(document).ready(function() {
var index = 0;
$('#show').click(function () {
$('div').eq(index).fadeIn('slow');
if(index < $('div').length){
index++;
}else{
alert('There is no more hidden content!');
}
});
$('#remove').click(function(){
$('div').eq(index -1).remove();
});
});
jQuery的.eq()
有一个zero based index
。我们在click函数之外设置了一个变量,但仍然可用于click的作用域,并按顺序切换隐藏内容。当我们单击时,它会将索引从0 > 1 > 2 > 3
更改,依此类推。我们检查索引是否小于与类hiddencontent
匹配的当前元素数,如果通过,则将索引迭代到下一个整数。
remove函数不需要更改迭代器,因为它只想删除最后一个索引项(根据您的场景,据我所知)。
这应该可以了。
发布于 2012-11-01 04:28:20
您可能可以尝试类似这样的方法
$("div:hidden").first().show();
和
$("div:visible").last().hide();
发布于 2012-11-01 04:25:12
下面的代码将显示第一个div和display none。
$(document).ready(function() {
$('#show').click(function () {
$("div").filter(function() {
return $(this).css("display") == "none"
}).first().show();
});
隐藏上次显示的div。
$('#remove').click(function () {
$("div").filter(function() {
return $(this).css("display") !== "none"
}).last().hide();
});
});
https://stackoverflow.com/questions/13166843
复制相似问题