javascript - 单击列表项应显示与该列表项相关的表格

标签 javascript jquery html

当用户选择列表项时,应显示与该列表项关联的表格。我有一个大脑障碍,我想我已经接近解决它或者至少是关于如何解决的想法。找到每个的长度,如果长度彼此相等,则创建显示/点击功能。答案应该是可以用于具有不同表格的数百个列表项。

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 

        })
    }
}

jsfiddle

最佳答案

如果您想仅根据列表项在列表中的位置将列表项关联到 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>

关于javascript - 单击列表项应显示与该列表项相关的表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43463484/

相关文章:

javascript - Three.js 的被遮挡对象行为异常

javascript - 对象 [object Object] 没有方法 'FixedScroll' Wordpress

html - 我如何从一个组件路由到 Angular 中另一个组件的一部分?

html - Grep linux 正则表达式在 html 源代码中

jquery - 如何使用 jquery 切换类淡入

javascript - 1 单击 html 后禁用 href?

javascript - 自定义模态脚本 - Safari 和 IE 问题

javascript - 在 Raphael.js 中更改 'color scheme'?

javascript - SVG:通过 jQuery 更新在 FF 中有效,但在 Safari 中无效,有什么想法吗?

javascript - Jquery Mobile 和 Cordova 事件 Pageinit 绑定(bind)不起作用