我有这个奇怪的问题。这是我的小提琴: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>
答案 0 :(得分: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) {
...