我有以下input
:
<input id="meepmeep" type="range" min="0" max="128" step="1" value="0" />
我正在做一个基本的setInterval()
电话:
setInterval(function() {
var newVal = $('#meepmeep').val() + 1;
$('#meepmeep').val(newVal);
}, 500);
但增加的val() + 1
似乎是val() + 50
任何想法?!
答案 0 :(得分:3)
该值被解析为String。 将数据类型转换为数字以解决问题:
setInterval(function() {
var newVal = parseInt($('#meepmeep').val()) + 1;
$('#meepmeep').val(newVal);
}, 500);
答案 1 :(得分:1)
那是因为.val()
返回一个字符串,你应该在添加之前将字符串转换为数字:
setInterval(function() {
$('#meepmeep').val(function(i, str) { return ++str; });
}, 500);
答案 2 :(得分:1)
这是一个通用函数,它将在给定jQuery元素的范围内滑动到给定值。
$("button").on("click", function(){
slideToValue(75, $("#slider"));
});
function slideToValue(num, $input) {
const interval = function() {
const cur = $input.val();
if (cur < num) {
console.log(`Value is ${cur}. Incrementing!`);
$input.val(parseInt(cur) + 1);
} else if (cur > num) {
console.log(`Value is ${cur}. Decrementing!`);
$input.val(parseInt(cur) - 1);
} else {
console.log(`Arrived at ${num}!`);
clearInterval(slowly);
}
}
const slowly = setInterval(interval, 10);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Set to 75</button>
<input type="range" id="slider">
答案 3 :(得分:0)
setInterval(function() {
var newVal = parseInt($('#meepmeep').val()) + 1.0;
$('#meepmeep').val(newVal);
}, 500);
工作正常;)
答案 4 :(得分:0)
var newVal = $('#meepmeep').val() + 1;
<强>结果强>
Run
1st time value = 1
2nd time = 11
3rd time = 111
4th time = 1111
因为您要添加string
而不将其转换为integer value
更正代码 Jsfiddle
setInterval(function() {
var newVal = $('#meepmeep').val(function(i, val) {
return +val + 1;
});
}, 500);
setInterval(function() {
var newVal = parseInt($('#meepmeep').val()) + 1;
$('#meepmeep').val(newVal);
}, 500);