javascript - 将 jQuery 中的元素隐藏在表格内

标签 javascript jquery html-table jquery-selectors

我有一个包含 trtd 的表格。我的 td 有一个 div 作为其子项。一个 div 具有 id="question",另一个 div 具有 id="answer"。我希望在遍历 td 时,隐藏具有 id="answer"div 。当页面加载时,只有问题 div 才会出现。这是html的结构

<td style="display: none;">
    <div style="border-color: #000000;position: relative;float: right;margin-top: 2px;right: 12%;"> </div>
    <div style="border-color: #000000;position: relative;float: right;margin-top: 2px;right:-2%;"> </div>
    <div id="question">
        <img id="faqGrid:0:j_idt77" height="10" width="480" src="/TDAP/faces/javax.faces.resource/spacer/dot_clear.gif?ln=primefaces&amp;v=2.2.RC2">
        <br>
        <br>
    <div id="answer">
    <div class="horizontalline"></div>
</td>

我做了以下事情。但它隐藏了整个 td。

$('#faqGrid tr td').each(function(){

    var $cells = $();

   /**
    *Gives you all children as an object array
    * 0: div
    * 1: div
    * 2: div#question
    * 3: img#faqGrid:0:j_idt77 /TDAP/fa...=2.2.RC2
    * 4: br
    * 5: br
    * 6: div#answer
    * 7: div.horizontalline
    */
    var tdChildrenArray = $(this).children();

    var divChildrenArray = $(this).children('div');

    var elementStack;

    $.each(divChildrenArray, function(index, value){

       var $div = value;

       if ($div.id) {

           var $divId = $div.id;

           if ($divId == 'answer') {

              var colNum = $(this).cellIndex;
              $cells = $cells.add($div);

           } //end of if ($divId == 'answer')

       } //end of if ($div.id)

    }); //end of  $.each(object, fn)

    return $(this).pushStack($cells);

}).hide(); //end of $('#faqGrid tr td').each(fn)

我的想法是,推送堆栈上的 div 只应该隐藏,但这不是真正的输出。

最佳答案

如果您有多于一行,则不应使用多个 ID 属性。将其更改为类...

<div class="question">
    <img id="faqGrid:0:j_idt77" height="10" width="480" src="/TDAP/faces/javax.faces.resource/spacer/dot_clear.gif?ln=primefaces&amp;v=2.2.RC2">
    <br>
    <br>
<div class="answer">

然后您可以执行这个简单的 JQuery 来隐藏答案元素...

$(".answer").hide();

为了直接回答您的问题,无论如何,您都会在 TD 元素集合上调用 .hide() 函数。

您可以将 .hide() 从最后移动并放入此行...

if ($divId == 'answer') {

    $div.hide();//hide your answer element
    var colNum = $(this).cellIndex;
    $cells = $cells.add($div);

} //end of if ($divId == 'answer')

...但是对于如此简单的事情来说,这是太多的代码

编辑:A Sample of what you might be trying to do

关于javascript - 将 jQuery 中的元素隐藏在表格内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8894471/

相关文章:

javascript - 在javascript中访问父对象

javascript - 使 DIV 在单击时向上显示

javascript - 如果结果为空,则禁用提交按钮 typeahead.js

javascript - setInterval 道场示例

javascript - 将文件流下载为 angularjs 中的文件

javascript - 菜单中点击事件的问题

javascript - 如何参数化对象的属性以便在 crossfilter.js 中使用?

css - 将多个元素放置在列的右侧

php - 从 PHP 表中一次更新多个 mysql 条目

html - css,带有垂直标题的表格