我有一个包含行的表,我试图隐藏所有孩子,除了第一个孩子,直到你点击一个按钮。到目前为止,这是我的代码:
console.log(shipmentNumbers);
for (let i = 0; i < shipmentNumbers.length; i += 1) {
let sNumber = shipmentNumbers[i];
console.log($('#status' + sNumber))
$('#status' + sNumber).on('click', getHistory);
var flagMore = false;
$("#shipmentTable:not(:first-child)").hide();
$("#more-button" + sNumber).on('click', function () {
$('#shipment' + sNumber + ' tr.showmore').show();
$(this).hide();
$("#fewer-button" + sNumber).show();
flagMore = true;
});
$("#fewer-button" + sNumber).on('click', function () {
$('#shipment' + sNumber + ' tr.showmore').hide();
$(this).hide();
$("#more-button" + sNumber).show();
flagMore = false;
});
}
我期望$(“#shipmentTable:not(:first-child)”)只显示货件表的第一个孩子,并隐藏其余部分。但是,这会隐藏所有内容,以便不显示任何表格行。我究竟做错了什么?
这是我的HTML:
var shipmentBodyItems = '';
for (let i = 0; i < shipment.itemDetails.length; i += 1) {
shipmentBodyItems += `<tr id="shipmentTable">
<td class="item-name"> ` + shipment.itemDetails[i].title + `</td>
<td class="item-qty"> ` + shipment.itemDetails[i].qty + `</td>
</tr>`;
}
答案 0 :(得分:0)
试试这个: -
$(document).ready(function(){
$("#btnSubmit").click(function(){
$("#myTbl tr:first-child").hide();
});
});
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<table id="myTbl" style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
<button name="btn" id="btnSubmit" type="button">Click Me!</button>
&#13;
答案 1 :(得分:0)
答案 2 :(得分:0)
$("#shipmentTable:not(:first-child)")
并不是个坏主意
唯一的问题是,id
需要独一无二!
将其更改为$(".shipmentTable:not(:first-child)")
会使其正常工作。
请参阅代码段:
// Added to have some data
var shipment = {
itemDetails: [{
title: "title 1",
qty: "1"
},
{
title: "title 2",
qty: "2"
},
{
title: "title 3",
qty: "3"
}
]
}
var shipmentBodyItems = '';
for (let i = 0; i < shipment.itemDetails.length; i += 1) {
// Here, I changed tr "id" to "class" !
shipmentBodyItems += `<tr class="shipmentTable">
<td class="item-name"> ` + shipment.itemDetails[i].title + `</td>
<td class="item-qty"> ` + shipment.itemDetails[i].qty + `</td>
</tr>`;
}
$('table tbody').html(shipmentBodyItems); // Added to have something visual
// Your code wasn't bad, the only mistake was using id instead of class
// (id needs to be unique!)
$(".shipmentTable:not(:first-child)").hide();
&#13;
table,
td {
border: 1px solid black;
border-collapse: collapse;
padding: 8px 16px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table id="#shipmentTable">
<tbody>
</tbody>
</table>
</body>
&#13;
我知道这是一个古老的话题,但无论如何......
希望它有所帮助!