使用JavaScript动态隐藏/显示表列

时间:2017-03-20 14:37:45

标签: javascript php html-table

我有一个按钮,当我按下它时,我必须在我的桌子上显示一个隐藏的列。但我的问题是我只显示一行。

<a href="#" class="btn-xl btn-default" id="btn_callkit" onclick="call();return false;" style="width: 150px;color: white;">KIT</a> 
 <table id="example0" class="table  table-striped">

        <br/>
            <thead>
                <tr>
                    <th id="kit_head" style="display:none;">KIT</th>
                    <th>Material</th>
                    <th>Info</th>
                 </tr>
             </thead>

                    <?php
                        $rol = mysql_query("SELECT * from pg  WHERE pg.dataset = 2 ");
                            if (mysql_num_rows($rol) != 0) { 
                                while($item = mysql_fetch_array($rol)) { 


                                    $id = $item['id'];  
                                    $info = $item['info'];  
                                    $code = $item['lote_code'];
                    ?>

             <tr id="infodata_<?=$id;?>">


                    <td id="line" style="display:none;">

                        <div class="checkbox  checkbox-circle" style="text-align:center;margin-top:40px;">
                            <input id="check_<?=$id;?>" type="checkbox">
                            <label for="check_<?=$id;?>">

                            </label>
                        </div>

                    </td>

                    <td><?php echo $info;?></td>

                    <td><?php echo $code;?></td>


                </tr>
        <? }} ?>
        </tbody>
        </table>

我的Javascript有这段代码:

function call()
{
    document.getElementById('kit_head').style.display = 'block'; 
    document.getElementById('line').style.display = 'block'; 
}

我该怎么做才能显示我的数据库里面的所有行?

3 个答案:

答案 0 :(得分:1)

您正在使用单元格line的ID。

getElementById - 顾名思义 - 将返回单个元素,这将始终为true,因为ID仅供一次性使用。所以你的代码:

document.getElementById('line').style.display = 'block';

获取第一个匹配元素并将style属性设置为已定义。

相反,您应该使用class,它旨在指定许多相关元素或共享通用规则的元素。

然后你可以得到所有匹配的元素,循环它们并设置所需的样式属性。

DOM API公开了许多按类名检索元素的方法,您应该参考您想要支持的浏览器版本列表,并从可用的技术中选择适当的技术。

修改 作为旁注,KennyDope说正确的最佳做法是切换类以操纵样式。跟内联样式一样,跟踪和修改类要容易得多。

答案 1 :(得分:0)

最佳做法是切换类而不是内联样式。

您的代码将是这样的:

<table class="table table-striped">
    <tr>
        <td class="toggle">Toggle field</td>
        <td class="toggle">Toggle field</td>
        <td>Other field</td>
    </tr>
</table>

<button id="btn_callkit">toggle</button>

<script>
   function toggle (t) {
        var listTd = document.getElementsByClassName("toggle");
        var i;

        for (i = 0; i < listTd.length; i++) {           
            listTd[i].classList.toggle('hidden');
        }           
    }

    document.getElementById('btn_callkit').addEventListener('click', toggle);
</script>

答案 2 :(得分:0)

ServiceContract属性在页面上必须是唯一的。

相反,OperationContract属性,顾名思义,是一类对象,多个对象可以共享同一个类。

因此,如果要显示/隐藏列,则必须将每行中的特定id分配到同一个类,然后使用class通过Javascript操作。

注意,<td>返回一个对象数组,您必须遍历数组以更改每个对象的显示样式。