[英]How to show hidden table row on click of existing html table row?
我有一個使用 while 循環生成 HTML 表的 PHP 腳本。
echo'<table id="rideTable" style="width:100%; cursor:pointer;">
<tr>
<th>NAME</th>
<th>ARRIVAL CITY</th>
<th>DEPARTURE CITY</th>
<th>AVALIABLE SPACE</th>
<th>DEPARTURE Date</th>
<th>Price</th>
</tr>';
while($row = mysqli_fetch_array($query)){
$fburl = $row['fb_url'];
echo '<tr><td><a href='.$fburl.'>'.$row['Name'].'</a></td><td>'.$row['ArriveCity'].'</td><td>'.$row['DepartCity'].'</td><td>'.$row['Space'].'</td><td>'.$row['Date'].'</td><td>$'.$row['Price'].'</td></tr>
<tr id = "description"><td colspan="6"><p>Detailed Ride Description Goes Here</p></td></tr>';
}
echo'</table>';
這是顯示生成表的單行的屏幕截圖:
. 我的問題是:當用戶單擊表格行時,我如何才能做到這一點,在單擊的行下方可以看到描述行。 特別說明 *這是在 PHP 腳本中,因此可能需要將 Javascript 嵌入到echo語句中。
需要切換的行是 while 循環第三行中 id = description 的tr 。
我已經瀏覽了類似的問題,但無法為我的表格設置一個切換的表格行。
(可能的困難:使用 php 腳本創建的表,使用 while 循環生成的表)
更新
當前的Javascript代碼:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector("#rideTable").onclick = function() {
document.querySelector(".description").style.display = "table-row";
};
});
</script>
該腳本有點功能,但是在第二次單擊表格時,描述不會切換為不可見。 此外,click 事件跟蹤整個表,而不是單個行; 這意味着,您在表格上單擊的任何位置都會使第一個描述可見。 我想讓當您單擊特定行時,該行的描述在可見/隱藏之間切換。
首先,你的代碼在某種程度上是無效的,因為你寫了類似的東西
id = description
在foreach循環中。 如果循環有不止一次迭代怎么辦? 會有用相同的ID不止一個HTML元素,它是不可接受的(不僅是語義上無效,而且也使元素難以用JavaScript訪問)。 請考慮使用class屬性而不是id 。
您還應該注意 PHP 和 Javascript 之間沒有聯系。 第一個只是一種服務器端語言,用於生成一些 HTML 代碼。 后者是一種客戶端語言,您很可能會將它插入到 HTML 文檔中的某個位置 - 文檔是否使用 PHP 生成並不重要。
最后,你的問題的答案是一段 JS 代碼:
document.querySelector("#rideTable").onclick = function() {
document.querySelector("#description").style.display = "table-row";
}
但在此之前,您應該使用 CSS 來隱藏這一行:
#description {
display: none;
}
好的,這是您更新的問題的答案。 我將使用 JQuery,因為它會使它更加干凈和簡單。 您必須在此新腳本之前將此庫添加到您的文檔中(舊腳本不正確),即:
$(function() { // we make sure that document is ready
$("#rideTable .clickable").click( function() { // and once the odd row (.clickable) is clicked
// we get the index of the row
var index = $("#rideTable .clickable").index(this);
// and using this index we get the row with description (.description) and toggle it.
$("#rideTable .description").eq(index).toggle();
});
});
還要更改您的 PHP 代碼,以便每個奇數行都有可點擊的類:
echo '<tr class="clickable"><td><a href='.$fburl.'>'.$row['Name'].'</a></td><td>'.$row['ArriveCity'].'</td><td>'.$row['DepartCity'].'</td><td>'.$row['Space'].'</td><td>'.$row['Date'].'</td><td>$'.$row['Price'].'</td></tr>
<tr class="description"><td colspan="6"><p>Detailed Ride Description Goes Here</p></td></tr>';
希望它對你有用:)。
更改
.... .style.display = "table-row";改成
.... .style.display = "block";style.display = "無"; 隱藏項目
style.display = "塊"; 顯示項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.