使用 jQuery 显示/隐藏表格 [英] Show/hide tables with jQuery

查看:46
本文介绍了使用 jQuery 显示/隐藏表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列类似于以下html代码的表格:

I have a series of tables similar to the following html code:

<table id="film"><tr>
       <th class="1">//HEAD CONTENT 1//</th>
       </tr>
       <tr>
       <td class="1">//BODY CONTENT 1//</td>
       </tr></table>
<table id="film"><tr>
       <th class="2">//HEAD CONTENT 2//</th>
       </tr>
       <tr>
       <td class="2">//BODY CONTENT 2//</td>
       </tr></table>

我希望在单击相应的头部 () 时单独展开表格.此外,表格应该开始时未展开.我使用以下 jQuery 脚本:

I want the tables to expand individually when the respective head (<th>) is clicked. Moreover the tables should start unexpanded. I use the following jQuery script:

$(document).ready(function(){
    $('#film td').hide();
});

$(document).ready(function(){
var n1 = 0;
      $('#film th.1').click(function(){
         if(n1 == 0){
         $('#film td.1').show();
         n1 = 1;
         }else{
        $('#film td.1').hide();
         n1 = 0;}
       });
var n2 = 0;
      $('#film th.2').click(function(){
         if(n2 == 0){
         $('#film td.2').show();
         n2 = 1;
         }else{
        $('#film td.2').hide();
         n2 = 0;}
       });
});

但是,当我仅执行顶部表格时,无法显示/隐藏第二个表格.谁能看出我哪里出错了?

However when I execute only the top table is able to show/hide not the second one. Can anyone see where I'm going wrong?

推荐答案

您在多个元素上使用相同的 ID.当您按 id 搜索时,jQuery 将只返回一个项目(具有该 id 的第一个项目).所以你的代码只作用于第一个表.在表上使用类而不是 id.

You are using the same id on multiple elements. When you search by id, jQuery will only return one item (the first with that id). So your code is only acting on the first table. Use a class on the tables instead of an id.

<table class="film">......</table>

$('.film').each(function(f) {
    //this function will execute for each element with the class "film"
    //refer to the current element during this function using "$(this)"
});

这篇关于使用 jQuery 显示/隐藏表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆