当用户选择列表项时,应显示与该列表项关联的表。我有脑筋,我想我已接近解决它或者至少是关于如何解决问题的想法。找到每个的长度,如果长度彼此相等,则创建显示/单击功能。答案应该是可以用于具有不同表的数百个列表项的答案。
HTML
<div>
<ul>
<li id='one'><a href="#">number</a></li>
<li id='two'><a href="#">othernumber</a></li>
</ul>
</div>
<div>
<table>
<thead>
<tr>
<th>title</th><th>title</th><th>title</th><th>title</th>
</tr>
</thead>
<tbody id="table1">
<tr>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
</tr>
</tbody>
<tbody id="table2" style="display:none">
<tr>
<td>blahTwo</td>
<td>blahTwo</td>
<td>blahTwo</td>
<td>blahTwo</td>
</tr>
</tbody>
</table>
</div>
JS
function count(){
var list = jQuery('ul li')
var table = jQuery('table tbody')
if(table.length == list.length){
jQuery(list).click(function(){
//show the table length that is equal to the list length
})
}
}
答案 0 :(得分:6)
如果您想根据列表中的位置将列表项与tbody元素相关联,则可以将.index()
method与.eq()
结合使用:
var list = jQuery('ul li a')
var table = jQuery('table tbody').hide()
list.click(function(e) {
table.hide().eq(list.index(this)).show()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<ul>
<li id='one'><a href="#">number</a></li>
<li id='two'><a href="#">othernumber</a></li>
</ul>
</div>
<div>
<table>
<thead>
<tr>
<th>title</th>
<th>title</th>
<th>title</th>
<th>title</th>
</tr>
</thead>
<tbody id="table1">
<tr>
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
</tr>
</tbody>
<tbody id="table2" style="display:none">
<tr>
<td>blahTwo</td>
<td>blahTwo</td>
<td>blahTwo</td>
<td>blahTwo</td>
</tr>
</tbody>
</table>
</div>