jquery 中有很多添加和删除的示例。 但我的代码与示例有点不同。当我单击“添加”时,它会显示第二个,如果我再次单击“添加”,我要显示第三个,当我单击“删除”时,也会隐藏第三个,直到第五个。这是我的代码
CSS
#second {
display: none;
}
#third {
display: none;
}
#forth {
display: none;
}
#fifth {
display: none;
}
HTML
<div id="header">
<a href="#" id="add1">add</a> - <a href="#" id="remove">remove</a>
<div id="first"><a href="#">first</a></div>
<div id="second"><a href="#">second</a></div>
<div id="third"><a href="#">third</a></div>
<div id="forth"><a href="#">forth</a></div>
<div id="fifth"><a href="#">fifth</a></div>
</div>`
JavaScript
$(document).ready(
function() {
$("#add1").click(function() {
$("#second").show();
});
$("#remove").click(function() {
$("#second").hide();
});
});
这是代码 JSfiddle
最佳答案
这是您可以使用的方法。首先,为要显示/隐藏的所有元素添加一个类。在本例中,我使用了类 toggle
:
<div id="header">
<a href="#" id="add1">add</a> - <a href="#" id="remove">remove</a>
<div id="first" class="toggle"><a href="#">first</a></div>
<div id="second" class="toggle"><a href="#">second</a></div>
<div id="third" class="toggle"><a href="#">third</a></div>
<div id="forth" class="toggle"><a href="#">forth</a></div>
<div id="fifth" class="toggle"><a href="#">fifth</a></div>
</div>
然后,当您添加元素时,使用函数 first
查找第一个具有类 toggle
的不可见元素并显示它。当你想删除元素时,使用函数last
找到最后一个不可见的元素并将其隐藏:
$(document).ready(function() {
// when add is clicked, show first not visible element with class 'toggle'
$("#add1").click(function() {
$('.toggle:not(:visible)').first().show();
});
// when remove is clicked, hide last visible element with class 'toggle'
$("#remove").click(function() {
$('.toggle:visible').last().hide();
});
});
关于javascript - 使用 jquery 显示和隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33623440/