【问题标题】:unknown if statement in javascriptjavascript中的未知if语句
【发布时间】:2018-09-20 07:18:07
【问题描述】:

if(td) 条件在这里做什么?编写此代码是为了在表中搜索一行。 var input 是搜索框,var table 是表格。

function myFunction() {
    // this function filters the table using search box
    var input, filter, table, tr, td, i;

    input = document.getElementById("myInput"); // the search box
    filter = input.value.toUpperCase();
    table = document.getElementById("myTable"); // the table
    tr = table.getElementsByTagName("tr");      // the row of table

    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        if (td) {  // why do we need this condition here?
            if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }       
    }
}

【问题讨论】:

  • 如果一行没有&lt;td&gt; 元素,那么变量将为undefined。

标签: javascript html if-statement filtering


【解决方案1】:

if (td) 代码检查以确保 td 中有某些内容并且它是真实的,以便您的下一行在查找 td.innerHTML 时不会引发错误。

【讨论】:

    【解决方案2】:

    td 包含该行的数据,并且您正在将数据与某个过滤器匹配。现在如果td不存在怎么办,你会得到undefined的错误

    【讨论】:

      【解决方案3】:

      docs

      Element.getElementsByTagName() 方法返回具有给定标签名称的元素的实时 HTMLCollection。

      结果是找到的元素按照它们在子树中出现的顺序的实时 HTMLCollection。如果没有找到任何元素,(在你的情况下,如果有一个 &lt;tr&gt; 里面没有一个 &lt;td&gt;)HTMLCollection 是空的。

      如果现在您得到一个空的 HTMLCollection,那么您调用下一行的 innerHTML 方法将导致以下错误,并且您的代码将中断。

      “类型错误:td 未定义”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-11
        • 1970-01-01
        相关资源
        最近更新 更多