尝试隐藏表格行时出现 JavaScript 错误

标签 javascript css xhtml

我试图根据用户的选择显示行。假设他只想要 3 行,那么第四和第五行将隐藏。请在下面找到 html 和 javascript 的部分。

HTML

<table>
  <tr id="sRow1">
    <td>1a</td>
    <td>1b</td>
  </tr>
  <tr id="sRow2">
    <td>2a</td>
    <td>2b</td>
  </tr>
  <tr id="sRow3">
    <td>3a</td>
    <td>3b</td>
  </tr>
  <tr id="sRow4">
    <td>4a</td>
    <td>4b</td>
  </tr>
  <tr id="sRow5">
    <td>5a</td>
    <td>5b</td>
  </tr>
</table>

JavaScript

// b gets value from xml file        
    while (b <= 5)
    {
        var rowName = "sRow" + b;
        alert(rowName);
        try {
            document.getElementById(rowName).style.display = "none";
        }
        catch (err)
        {
            alert(err.description)
        }
        b++;
    }

我在 document.getElementById(rowName).style.display = "none"; 收到 Object required 错误。你能帮忙吗?

最佳答案

你错过了有趣的一点(b 的来源),所以我只是猜测:有时 b 不是t 实际上是 1 到 5 之间的数字(含 1 和 5)。也许它是一个不能完全格式化为一位数字 1-5 的字符串,或者它可能完全是其他东西……让我们让您的代码更安全一些,以防万一我是对的:

// b gets value from xml file

// ensure b is a number - will fail comparison if NaN
b = new Number(b);
while (b <= 5)
{
  var rowName = "sRow" + b;
  var row = document.getElementById(rowName);
  if ( row ) // verify element was found before trying to modify it!
    row.style.display = "none";
  b++;
}

请注意,我已经删除了 try {} catch - 您最好只测试 getElementById() 的返回值,因为那样不会干扰如果您以后希望使用调试器...

关于尝试隐藏表格行时出现 JavaScript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1435967/

相关文章:

JavaScript 和 html 幻灯片

javascript - 在字符串替换中使用正则表达式的一句话得到的字符数

javascript - for 循环的 xhr 响应不起作用

css - 如何设置放大的响应图像?

javascript - 在javascript中单击按钮更改文本并替换按钮/文本?

javascript - 将 Jquery 选择器的名称设置为变量中的字符串

css - 以站点标题为中心的标志 Wordpress

css - 这些 css 属性你用过吗?

jquery - 如何使用 jquery 将图像标题渲染为灯箱标题?

xhtml - rel 属性中的 "me"是什么意思?