繁体   English   中英

根据表格的行数隐藏或显示按钮

[英]Hide or display a button according to row count of a table

我有一个HTML表和一个按钮发送。

首先,发送按钮必须具有以下样式: style.display="none"

但是如果表中至少有一行,则应该显示该按钮( block / inline );

我仍然不知道如何在表格和按钮之间建立联系。 我尝试使用JavaScript,但我应该考虑一个函数,但我发现其中没有一个适用于类型表。 由于找不到表和按钮之间的关系,因此思考CSS仍然很困难。

调整表格后,您需要切换按钮的可见性。 由于可以通过多种方式完成此操作,因此无法知道哪种方法适合您。

为了简单起见,请尝试一下jQuery 与“普通” JavaScript相比,访问元素和修改样式要容易得多。 还请确保,如果要在页面加载后通过JavaScript更新表,则在每次执行此操作时都使用它。

$(document).ready(function(){
   if ($("#table > tr").length > 0)
      $("#button").show();
   else
      $("#button").hide();
});

希望对您有所帮助。

一个与Lance May的答案完全相同的,非jquery的形式将是这样的:

var button = document.getElementById('the-button');
if (document.getElementById('the-table').getElementsByTagName('tr').length > 0){
  button.style.display = 'block';
}else{
  button.style.display = 'none';
}

如果Button位于最定义的TD内。 然后只需通过以下方式访问它:

td input {
  display: none;
}

您甚至可以在CSS3中使用高级选择器来定义样式

input[type="button"] {
  display: none;
}

我在博客上写了这个。

使用JavaScript,您可以使用

var myInput = document.getElementsByTagName('input');
myInput.style.display = none;

要在tr中选择输入,请使用类似

myTableRow.childNodes[0];
<html>
<head>
 <title>whatever</title>
 <style type="text/css">
  .hidden {
   display: none;
  }
 </style>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
 <script type="text/javascript">
  $(document).ready(function ()
  {
   var $t = $('table');
   var $h = $t.find('thead');
   var $b = $t.find('tbody');
   var $s = $('#send');

   // the "add" button appends a new row
   // into the table body; if the body
   // transitions from empty, the "send"
   // button is displayed
   $('#add').bind('click', function ()
   {
    $b.append(newRow());
    if (1 == $b.find('tr').length)
     $s.removeClass('hidden');
   });
   // the remove button removes the last
   // row from the table body (if there's
   // any); if the body transitions to
   // empty, the "send" button is hidden
   $('#remove').bind('click', function ()
   {
    $b.find('tr:last').remove();
    if (0 == $b.find('tr').length)
     $s.addClass('hidden');
   });
   // generates a table row; this demo
   // impl. just copies the heading row
   var newRow = function ()
   {
    return $h.find('tr').clone();
   };
  });
 </script>
</head>
<body>
 <table border="1">
  <thead>
   <tr><td>foo</td><td>bar</td></tr>
  </thead>
  <tbody>
  </tbody>
 </table>
 <input type="button" id="add" value="add" />
 <input type="button" id="remove" value="remove" />
 <input type="button" id="send" value="send" class="hidden" />
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM