我正在寻找一种搜索列的动态方法,当值更改时,应插入新行。
考虑下表:
<table id="testTable">
<tbody>
<tr>
<th>Letter</th>
<th>Amount</th>
</tr>
<tr>
<td class="parent">A</td>
<td>110</td>
</tr>
<tr>
<td class="parent">A</td>
<td>99</td>
</tr>
<tr>
<td class="parent">A</td>
<td>106</td>
</tr>
<tr>
<td class="parent">A</td>
<td>120</td>
</tr>
<tr>
<td class="parent">C</td>
<td>103</td>
</tr>
</tbody>
</table>
当遇到父类中从“A”变为“C”的变化时,我想在“C”之前插入一行或者可能与之前的任何值不同。我有点开始用这个来捕获一些数据,但还没有走得太远:
$('#' + value + ' .parent').each(function () {
var firstVal = $(this).html();
var secondVal = $(this).next().html();
if(firstVal == secondVal) {
}
else {
$(this).parent().after('</tr><tr><td class="sub0">Sub Total</td></tr>');
}
})
请参阅我的JSFiddle
答案 0 :(得分:1)
你需要做的就是比较值和prepend这样的行:
let prev = "";
$('.parent').each(function() {
let test = $(this).text();
if(test != prev && prev != ""){
//$(this).prepend('<tr><td class="separator"><hr></td></tr>');//add it to the same row...
$(this).parent().before('<tr><td colspan="2" class="separator"><hr></td></tr>');
}
prev = test;
//console.log(test);
});
答案 1 :(得分:1)
$(document).ready(function(){
var lastVal = '';
$('#testTable .parent').each(function () {
var currentVal = $(this).html();
if(currentVal != lastVal) {
$(this).parent().before('</tr><tr><td class="sub0">Sub Total</td></tr>');
lastVal = currentVal;
}
});
});
答案 2 :(得分:1)
您的代码稍作修改即可。
$(document).ready(function() {
var lastVal = '';
$('#testTable .parent').each(function() {
var currentVal = $(this).html();
if (currentVal != lastVal) {
$(this).parent().before('</tr><tr><td class="sub0">Sub Total</td></tr>');
lastVal = currentVal;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="testTable">
<tbody>
<tr>
<th>Letter</th>
<th>Amount</th>
</tr>
<tr>
<td class="parent">A</td>
<td>110</td>
</tr>
<tr>
<td class="parent">A</td>
<td>99</td>
</tr>
<tr>
<td class="parent">A</td>
<td>106</td>
</tr>
<tr>
<td class="parent">A</td>
<td>120</td>
</tr>
<tr>
<td class="parent">C</td>
<td>103</td>
</tr>
</tbody>
</table>
答案 3 :(得分:0)
var perent = $('.parent');
$.each(perent, function(i, y) {
if ($(perent[i]).html() != $(perent[i + 1]).html()) {
$(this).parent().after('</tr><tr><td class="sub0">Sub Total</td></tr>');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="testTable">
<tbody>
<tr>
<th>Letter</th>
<th>Amount</th>
</tr>
<tr>
<td class="parent">A</td>
<td>110</td>
</tr>
<tr>
<td class="parent">A</td>
<td>99</td>
</tr>
<tr>
<td class="parent">A</td>
<td>106</td>
</tr>
<tr>
<td class="parent">A</td>
<td>120</td>
</tr>
<tr>
<td class="parent">C</td>
<td>103</td>
</tr>
</tbody>
</table>