如何在列表中添加隐藏/显示元素的函数?
例如,我们有几个列表。当我们点击“显示”链接时,所有的列表项都会显示出来,当我们点击“隐藏”链接时,就会隐藏索引大于3的列表中的项目。
<div class="filter_item">
...
<h3>Network Name:</h3>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
...
</div>和js代码
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function($){
$('.filter_item ul').each(function(){
$('li:gt(2)', this).hide();
if ($(this, 'li').children().length > 3) {
$(this, ':last').append('<li><a href="javascript:void(0);" class="tr_more">More...</a></li>');
}
});
$('.tr_more').toggle(function(){
$(this).closest('li').siblings().show();
$(this).attr('class', 'tr_less').text("Less...");
}, function(){
????
});
});
//]]>
</script>如何实现当我们点击“隐藏”链接时隐藏项目?
发布于 2010-05-20 20:12:42
虽然这看起来过于复杂,但这对你来说是可行的:
$(this).closest('ul').children('li:gt(2):not(:last)').hide();它首先搜索父<ul>,然后隐藏子<li>,但保留“显示/隐藏”链接的父链接。
使用$(this).closest('li').prevAll().slice(2).hide();并不是很有效-它隐藏了第一个节点,而不是最后一个节点。prevAll似乎以相反的顺序返回元素。
发布于 2010-05-20 20:49:45
您可以在前三个元素之后添加一个类到li元素,然后通过向ul父元素添加一个类来显示和隐藏它们,而不是单独显示和隐藏每个元素:
Javascript:
$(function(){
$('.filter_item ul')
.addClass('hidemore')
.each(function(){ $(this).find('li:gt(2)').addClass('more'); })
.append($('<li/>').append($('<a/>').attr('href','javascript:void(0)').text('more...')))
.find('a').toggle(function(){
$(this).text('less...').closest('ul').removeClass('hidemore');
},function(){
$(this).text('more...').closest('ul').addClass('hidemore');
});
});CSS:
.filter_item ul.hidemore li.more { display: none; }备注:
带有javascript:void(0)的href属性被添加到链接中,以便它们显示为链接,但不会导航到任何地方。这样,单击处理程序就不必停止事件。
添加元素后的.find('a')是因为在将元素添加到页面之后,才向元素添加单击事件处理程序。(如果列表中的文本还包含链接,则需要在添加的链接中添加一个类,以便在此阶段可以专门针对这些链接。)
发布于 2010-05-21 15:19:20
最终的代码如下所示
jQuery(document).ready(function($){
$('.filter_item ul').each(function(){
$('li:gt(2)', this).hide();
if ($(this, 'li').children().length > 3) {
$(this, ':last').append('<li><a href="javascript:void(0);" class="tr_more">More...</a></li>');
}
});
$('.tr_more').toggle(function(){
$(this).closest('li').siblings().show();
$(this).attr('class', 'tr_less').text("Less...");
}, function(){
$(this).closest('ul').children('li:gt(2):not(:last)').hide();
var curr_ul_y_pos = $(this).closest('ul').prev().offset().top;
$('html:not(:animated), body:not(:animated)').animate({
scrollTop: curr_ul_y_pos-5
}, 'normal');
$(this).attr('class', 'tr_more').text("More...");
});
});在隐藏事件后添加忘记的属性。页面现在滚动到h3元素位置。
https://stackoverflow.com/questions/2873451
复制相似问题