在一组旋转器中,当一个旋转器的值发生变化时,更新其他旋转器的最大值

In a group of spinners, update other spinners max value on change of a spinner value

本文关键字:旋转 最大值 变化 更新 其他 一组 一个      更新时间:2023-09-26

我遇到过这样一个场景,我们有三个输入微调器,最初的最大值设置为20,现在如果任何一个微调器的值改变了,那么其他微调器的最大值也应该改变。例如:有三个spinner1, spinner2, spinner3, Max为20,如果最初spinner1被设置为3,那么spinner2和spinner3应该能够选择最大值直到17,现在是spinner2被设置为10,那么spinner3只能选择最大值7,现在如果spinner1再次被设置为1,那么spinner2和spinner3应该能够选择剩余的20-(1+10)值中的最大值

老实说,这类问题真的不适合SO。当一个人来这里寻求帮助时,我们通常期望他们自己做了合理的尝试来编写代码,但遇到了一个他们无法解决的特定问题。

我们还希望请求者展示他们遇到问题的实际代码,并能够清楚地说明他们代码的预期结果是什么,以及描述他们当前的尝试如何未能满足期望。

话是这么说的,我今天早上需要休息一下,所以请看看下面,它应该正好符合你的需要。查看代码,如果您对某些内容的工作方式有任何疑问,请随时提问:

$('.restrain').change(function(){
	var $this=$(this); // cache the spinner the user interacted with
    var $group=$(this).closest('.restrain-group'); // get the group that contains the spinner
    var maxAllowed=$group.data('restrain-group-max'); // get the group max from the data attribute on the container
    var $spinners=$.merge($group.find('.restrain').not(this), $this); // get all of the spinners for the current group, arrange the collection so that the current spinner is always last, this is VERY important
        
    var total=0; // store our running total
    $spinners.each(function(){
	    var $this=$(this); //cache the current spinner in the loop
        var curVal=Number($this.val()); // get the current spinner's value
        var newVal=total+curVal;// add the value to the running total
        if(newVal>maxAllowed){ // if the running  total is now higher than the maxAllowed, we've gone too high
            var adjustVal=newVal-maxAllowed; // figure out how much over the total we are
            var replacementVal=curVal-adjustVal; // subtract the overage from the current spinner's value
                replacementVal = replacementVal <0 ? 0 :replacementVal;
            $this.val(replacementVal); // set the current spinner to the lowered value
            curVal=replacementVal; 
        }
        total=total+curVal; // add the last value to the total before checking the next spinner
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="restrain-group" data-restrain-group-max="20">
    <input class="restrain" type="number" min="0"  step="2" value="6" size="6">
    <input class="restrain" type="number" min="0" step="2" value="6" size="6">
    <input class="restrain" type="number" min="0"  step="2" value="6" size="6">
</div>