gpt4 book ai didi

javascript - 将表结果迭代到具有相同类的不同 div

转载 作者:行者123 更新时间:2023-12-03 01:21:32 25 4
gpt4 key购买 nike

使用此代码....尝试从每个多个表中获取结果并将结果定位到具有相同类的div...每个表中的一个结果到每个div...而不添加任何id等等......并且不使用.after()。希望这是有道理的。您可以看到我设置的一些 console.logs...但似乎无法让它用正确的结果填充 div。

<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

//Get Number of Divs with class='sum'
var divN = $( ".sum" ).length;
console.log('Number of Divs in page that match class sum : ' + divN);

//Get Number of TDs with class='two'
var tdN = $( ".two" ).length;
console.log('Number of TDs in page that match class two : ' + tdN);

//Get Number of Tables
var tblN = $( "table" ).length;
console.log('Number of Tables in page : ' + tblN);

//Get Number of TDs with class='two' in each table
$("table").each(function(){
tblSum = $('.two', this).length;
console.log('Number of TDs that match class two in each Table : ' + tblSum);
});

//Get result from each table and place it in div class="sum"
$(".sum").text(tblSum);
});

</script>
</head>
<body>
<table>
<tr><td class="one">Test</td></tr>
<tr><td class="one">Test</td></tr>
<tr><td class="one two">Test</td></tr>
<tr><td class="one">Test</td></tr>
<tr><td class="one">Test</td></tr>
<tr><td class="one two">Test</td></tr>

</table>
<div class="sum"></div>
<table>
<tr><td class="one">Test</td></tr>
<tr><td class="one">Test</td></tr>
<tr><td class="one two">Test</td></tr>
<tr><td class="one">Test</td></tr>
<tr><td class="one">Test</td></tr>
<tr><td class="one">Test</td></tr>

</table>
<div class="sum"></div>

</body>
</html>

最佳答案

您可以使用 next() 函数,例如:

$(this).next('.sum').text(tblSum);

$(document).ready(function() {
$("table").each(function() {
var tblSum = $('.two', this).length;
$(this).next('.sum').text(tblSum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="one">Test</td>
</tr>
<tr>
<td class="one">Test</td>
</tr>
<tr>
<td class="one two">Test</td>
</tr>
<tr>
<td class="one">Test</td>
</tr>
<tr>
<td class="one">Test</td>
</tr>
<tr>
<td class="one two">Test</td>
</tr>

</table>
<div class="sum"></div>
<table>
<tr>
<td class="one">Test</td>
</tr>
<tr>
<td class="one">Test</td>
</tr>
<tr>
<td class="one two">Test</td>
</tr>
<tr>
<td class="one">Test</td>
</tr>
<tr>
<td class="one">Test</td>
</tr>
<tr>
<td class="one">Test</td>
</tr>

</table>
<div class="sum"></div>

关于javascript - 将表结果迭代到具有相同类的不同 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51751932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com