无法更改HTML元素的可见性

Unable to change the visibility of HTML elements

本文关键字:元素 可见性 HTML      更新时间:2023-09-26

我正在尝试更改一行元素的可见性。我应该只在用户选择按钮时显示元素。

HTML代码:

  <tr style="display:none">
      <td><input type="submit" value ="Home" onclick="" id="home"/></td>
      <td><input name="home_phone" id="home_phone" type="text" value="Phone" ></td>
  </tr>

JS代码:

 document.getElementById("home").style.display = '';
 document.getElementById("home_phone").style.display = '';

我正在尝试使用HTML和JS来实现这一点。

您的JavaScript代码是正确的。

问题是,您正在为嵌套在隐藏图元中的图元设置显示值。您必须更改<tr>的样式,因为它是隐藏的元素。

HTML代码:

<a href="javascript:toggleRow('home_row');">toggle home row visibility</a>
<table>
   <tr id="home_row">
      <td><input type="submit" value ="Home" onclick="" id="home"/></td>
      <td><input name="home_phone" id="home_phone" type="text" value="Phone" ></td>
   </tr>
</table>

JS代码:

function toggleRow(rowId){
    var rowElement = document.getElementById(rowId);
    rowElement.style.display = rowElement.style.display.toLowerCase() == 'hidden'
                               ? 'table-row'
                               : 'hidden';
}