gpt4 book ai didi

javascript - jQuery 每个元素都收集数据值并使用条件进行正确的输出

转载 作者:行者123 更新时间:2023-12-01 02:22:16 26 4
gpt4 key购买 nike

我在循环 HTML 元素、从数据点收集值并检查传递的值是否小于选择并显示正确的标题时遇到了一些问题。

var percentageScore = "43";

$('.quiz-score .final-result').each(function(index) {
if (percentageScore <= $(this).data('points')) {
var finalStatus = $(this).find('h3').text();
$('.final-score').text(finalStatus);
}
});
.final-result { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="quiz-score">
<div class="final-result" data-points="20">
<h3>
under 20
</h3>
</div>
<div class="final-result" data-points="40">
<h3>
between 21 and 40
</h3>
</div>
<div class="final-result" data-points="60">
<h3>
between 41 and 60
</h3>
</div>
<div class="final-result" data-points="80">
<h3>
between 61 and 80
</h3>
</div>
<div class="final-result" data-points="100">
<h3>
between 81 and 100
</h3>
</div>
</div>

<div class="final-score"></div>

最佳答案

你必须打破循环。

要中断 $.each() 循环,请返回 false

来自the docs :

Use return false to break out of each() loops early.

var percentageScore = "43";

$('.quiz-score .final-result').each(function(index) {
if (percentageScore <= $(this).data('points')) {
var finalStatus = $(this).find('h3').text();
$('.final-score').text(finalStatus);
return false;
}
});
.final-result { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="quiz-score">
<div class="final-result" data-points="20">
<h3>
under 20
</h3>
</div>
<div class="final-result" data-points="40">
<h3>
between 21 and 40
</h3>
</div>
<div class="final-result" data-points="60">
<h3>
between 41 and 60
</h3>
</div>
<div class="final-result" data-points="80">
<h3>
between 61 and 80
</h3>
</div>
<div class="final-result" data-points="100">
<h3>
between 81 and 100
</h3>
</div>
</div>

<div class="final-score"></div>

关于javascript - jQuery 每个元素都收集数据值并使用条件进行正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49117442/

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