2010-06-16 90 views
0

我有一個HTML表格和一個按鈕發送。根據表格的行數隱藏或顯示按鈕

首先發送按鈕必須有這種風格:style.display="none"

但是,如果表格中至少有一行,則應顯示按鈕(block/inline);

我仍然不知道如何關聯表和按鈕。 我嘗試使用JavaScript,但我應該考慮一個函數,並且我沒有發現它適用於類型表。思考CSS仍然很難,因爲我無法找到表和按鈕之間的關係。

+1

表格是如何填充行的?使用Javascript?某些服務器端技術(如果有的話)? – bezmax 2010-06-16 13:38:00

回答

1

在調整表格時,您需要切換按鈕的可見性。由於這可以通過很多方式完成,因此無法知道什麼適合您。

爲簡單起見,give jQuery a try。我將訪問元素並修改樣式比'vanilla'JavaScript更容易。另外請確保,如果您在頁面加載後(通過JavaScript)更新表格,那麼您在此時使用該表格。

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

我希望有幫助。

+0

這不是普通的香草JavaScript。這是jQuery。 OP可能會嘗試直接使用它,它不會工作。 – 2010-06-16 13:53:48

+0

對不起。我已經包含在文章的預編輯中。我建議使用jQuery,並簡化元素訪問和樣式修改。我想我刪除了太多呃?我會編輯回來。感謝您的提醒! – Lance 2010-06-16 14:04:09

+0

什麼意思OP正好 – kawtousse 2010-06-16 14:14:40

0

如果按鈕位於最明確定義的TD內。不那麼只需通過訪問:

td input { 
    display: none; 
} 

你甚至可以在CSS3

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

我在blog寫這個了先進選擇這樣定義stlye。

使用JavaScript,你可以抓住的輸入欄

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

要選擇輸入一個TR內,使用類似

myTableRow.childNodes[0]; 
1

一個普通的,非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'; 
} 
+1

你是我的英雄湯姆。 ;) – Lance 2010-06-16 14:09:00

-1
<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>