如何在 Jquery 中连续单击将隐藏行插入到表中



这是函数的html和jquery代码。它初始化第一行,所以现在我想在单击按钮时调用隐藏行,尽可能多地使用相同的按钮。这是我到目前为止的代码

<!-- Jquery button click function -->
$(function() {
$('button').click(function() {
$('#other_tr').show()
var clone =  $('#other_tr').clone;
$('#first_tr').after(clone)
})
});
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr id="first_tr">
			    <th>Unit price</th>
			    <th>Discount</th>
			    <th>Total</th>
			</tr>

<!-- hidden row -->
<tr id="other_tr" style="display: none;">
			    <th>Unit price</th>
			    <th>Discount</th>
			    <th>Total</th>
			</tr>
</thead>
</table>
<button>Fetch Row</button>
</body>
</html>

我认为这就是你所追求的,尽管我建议创建一个空tbody并将新行附加到其中。

$(function() {
$('button').click(function() {
var clone = $('#other_tr').clone();
$('table thead').append(clone);
clone.show();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr id="first_tr">
<th>Unit price</th>
<th>Discount</th>
<th>Total</th>
</tr>
<!-- hidden row -->
<tr id="other_tr" style="display: none;">
<th>Unit price</th>
<th>Discount</th>
<th>Total</th>
</tr>
</thead>
</table>
<button>Fetch Row</button>

<!-- Jquery button click function -->
$(function() {
$('button').click(function() {
$('#other_tr').show();
var clone =  $('#other_tr').clone();
$('#first_tr').after(clone);
})
});
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr id="first_tr">
			    <th>Unit price</th>
			    <th>Discount</th>
			    <th>Total</th>
			</tr>

<!-- hidden row -->
<tr id="other_tr" style="display: none;">
			    <th>Unit price</th>
			    <th>Discount</th>
			    <th>Total</th>
			</tr>
</thead>
</table>
<button>Fetch Row</button>
</body>
</html>

我建议您在页面加载时删除other_tr,删除其id,并存储在变量中。

然后每次克隆该变量

$(function() {
var $tr = $('#other_tr').detach().show().removeAttr('id');
$('button').click(function() {
$('#first_tr').after($tr.clone());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr id="first_tr">
<th>Unit price</th>
<th>Discount</th>
<th>Total</th>
</tr>
<!-- hidden row -->
<tr id="other_tr" style="display: none;">
<th>Unit price</th>
<th>Discount</th>
<th>Total</th>
</tr>
</thead>
</table>
<button>Fetch Row</button>

最新更新