dousi1906 2014-08-29 03:56
浏览 34
已采纳

如果找到值,JQuery将显示表行

This might seem similar to other questions, and I have found and read through those questions and tried them, but I haven't gotten a working solution as of course, my code is unique and I need maybe another set of eyes to help me find my bug.

Anyway, the problem:

I'm creating a table (with PHP), and essentially if a cell has a value, the row gets an id of 'foo' and is hidden (using CSS - display: none;), and when I click a checkbox I'm trying to display all those hidden rows.

<tr id='foo'><td>this row is hidden</td></tr>
<tr><td>this row is not hidden</td></tr>

My jQuery is currently this:

$("#showHiddenRows").click(function() {
    if($(this).is(":checked")) {
        alert("showing"); //This pops up
        $("#tableName").each(function() {
            if($("#tableName").find("tr").attr("id") === 'foo') {
                $("#tableName").find("tr").attr("style", "display: initial;");
                alert("found a hidden row"); //This does not pop up...
            }
        });
    } else {
        alert("hiding");
        //essentially the same code here, but display:none;
    }

So I added alerts as you can see, the "showing" and "hiding" alerts pop up, but the "found a hidden row" doesn't, implying that searching through my table doesn't find any rows with an ID of 'foo', and I'm not sure why. Is there a better way to do this/is this the best way, and if so what did I do wrong?

Thanks in advance!

Edit: Quick explanation of what I was intending the code to do:

  • Loop through each row in the tableName table
  • If you find a tablerow with an ID of 'foo', show or hide the row.
  • 写回答

3条回答 默认 最新

  • dongtai6741 2014-08-29 04:13
    关注

    Do not use duplicate IDs; use a CSS class instead. By definition, IDs should be unique; therefore no two or more elements should have the same ID.

    HTML:

    <tr class='foo'><td>this row is hidden</td></tr>
    <tr><td>this row is not hidden</td></tr>
    

    JS:

    $(function() {
        $("#showHiddenRows").on('change', function() {
            if( this.checked ) {
                $('table tr.foo').show();
            } else {
                $('table tr.foo').hide();
            }
        });
    });
    

    Or, you could shorten it like this:

    $(function() {
        $("#showHiddenRows").on('change', function() {
            $('table tr.foo')[ this.checked ? 'show' : 'hide' ]();
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘