【问题标题】:JQuery: Loop through multiple lists and hide more than 5 children for eachJQuery:遍历多个列表并为每个列表隐藏超过 5 个子项
【发布时间】:2016-02-27 05:12:19
【问题描述】:

我有一个表,其中包含无序列表,每个列表中有几十个列表项。这些列表共享同一个类。我想遍历每个列表,如果它有超过 5 个列表项,我想显示前 5 个并隐藏其余的并显示指向另一个页面的链接。

我的逻辑有问题,因为我只能对第一个无序列表执行上述操作,然后隐藏后面的所有其他列表。如果不超过 5 行,如何检查每个列表并中断并继续下一个?

以下是我尝试过的基本 HTML 和 JS。

提前感谢您的帮助!

	$('ul.resultsList').each(function () { 
 	        if($(this).children().length > 4) {
			$('li:gt(4)').hide();
			$('.seeMore').show();
		}else {
                        $('.seeMore').hide();
                        return false;
                }
	});
    <table id="docResults">
	<thead>
		<tr>
			<th>Names</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>
				<ul class="resultsList">
					<li>Smith, J</li>
					<li>Smith, F</li>
					<li>Smith, K</li>
					<li>Smith, L</li>
					<li>Smith, M</li>
					<li>Smith, N</li>
					<li>Smith, O</li>
					<li>Smith, P</li>
					<li>Smith, Q</li>
					<li>Smith, R</li>
				</ul>
				<a href="#" class="seeMore">
			</td>
		</tr>
		<tr>
			<td>
				<ul class="resultsList">
					<li>Smith, J</li>
					<li>Smith, F</li>
					<li>Smith, K</li>
					<li>Smith, L</li>
					<li>Smith, M</li>
					<li>Smith, N</li>
					<li>Smith, O</li>
					<li>Smith, P</li>
					<li>Smith, Q</li>
					<li>Smith, R</li>
				</ul>
				<a href="#" class="seeMore">
			</td>
		</tr>
	</tbody>
</table>

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    尝试在此上下文中使用$(this) 对象来调用.hide()

    $('ul.resultsList').each(function () { 
     var td = $(this).closest("td");
     if($(this).children().length > 4) {
       $('li:gt(4)', this).hide();
       $('.seeMore', td).show(); 
     }else {
       $('.seeMore', td).hide();
     }
    });
    

    DEMO

    【讨论】:

    • 谢谢@rajaprabhu-aravindasamy!它完全有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多