0

我有这个奇怪的问题。这是我的小提琴:http: //jsfiddle.net/m6qJC/7/

正如你所看到的,它应该取第一个滑块的值,然后是第二个,做一些计算并打印结果。但是,当您将滑块(第一个,第二个不这样做)快速移动到一端或另一端时,它会计算出奇怪的东西。请看一下。请问有解决方案吗?

$(document).ready(function () {
    $("#amount_slider").slider({
        orientation: "horizontal",
        range: false,
        min: 500,
        max: 4999,
        value: 500,
        step: 10,
                animate: 'slow',
                slide: function (event, ui) {
            $("#amountDisp").text(ui.value);
            calculate();
        }
    });
    $("#time_slider").slider({
        orientation: "horizontal",
        range: false,
        min: 7,
        max: 28,
                step: 7,
        value: 7,
                animate: true,
                slide: function (event, ui) {
            $("#timeDisp").text(ui.value);
            calculate();
        }
    });
    function calculate() {
        var amount = parseInt($("#amount_slider").slider("value"));
        var time = parseInt($("#time_slider").slider("value"));
                var coeficient = 0;
                switch(time){
                       case 7: coeficient = 1.09;break;
                       case 14: coeficient = 1.15;break;
                       case 21: coeficient = 1.19;break;
                       case 28: coeficient = 1.25;break;
                       }
        var rate = amount * coeficient;
        $("#result").text(rate.toFixed(2));
    }   
});

和html:

<p>Money: <span id="amountDisp">500</span><div id="amount_slider"></div></p><p>Time: <span id="timeDisp">7</span><div id="time_slider"></div></p><p>Calculated <span id="result">545</span></p>
4

1 回答 1

1

.slider("value")滑块的值在您用于获取它的位置尚未更新。它仅在幻灯片事件完成后更新,因此计算使用前一个值而不是当前值。

一个快速的解决方法是将值作为参数传递:

// in the amount slider event
calculate(parseInt(ui.value, 10), parseInt($("#time_slider").slider("value"), 10));

// in the time slider event
calculate(parseInt($("#amount_slider").slider("value"), 10), parseInt(ui.value, 10));

function calculate(amount, time) {
   ...

演示:http: //jsfiddle.net/m6qJC/9/

于 2013-05-19T08:09:09.730 回答