Javascript 减少整数工作,相同的增加整数不可用
增加和减少应使当前值增加或减少0.1。它们的设置相同。出于某种原因,“减少”1.0将变为0.9、0.8等,但“增加”1.0不会变为1.00.1,就像它连接字符串一样 我尝试过使用parseInt和parseFloat,但在增加新值=当前值+0.1时运气不佳,但减少确实有效新值=当前值-0.1 我希望两者都能工作,而不是像这样设置 HTML: 小提琴: .toFixed1将数字转换为字符串 将数字添加到字符串时,数字会隐式转换为字符串,从而将“0.1”字符串添加到末尾 减法对字符串不起作用,因此其行为有点不同:字符串将隐式转换为数字Javascript 减少整数工作,相同的增加整数不可用,javascript,jquery,Javascript,Jquery,增加和减少应使当前值增加或减少0.1。它们的设置相同。出于某种原因,“减少”1.0将变为0.9、0.8等,但“增加”1.0不会变为1.00.1,就像它连接字符串一样 我尝试过使用parseInt和parseFloat,但在增加新值=当前值+0.1时运气不佳,但减少确实有效新值=当前值-0.1 我希望两者都能工作,而不是像这样设置 HTML: 小提琴: .toFixed1将数字转换为字符串 将数字添加到字符串时,数字会隐式转换为字符串,从而将“0.1”字符串添加到末尾 减法对字符串不起作用,因此其
在进行加法或减法运算后,您需要调用.toFixed。解决此“问题”的方法过于复杂,可以返回到非常简单的代码。首先更改数据方向的值
<button data-direction="1">increase</button>
<button data-direction="-1">decrease</button>
为了安全起见,我会对键入的值等进行检查。。。但这要由你决定。希望它能帮助…
$function{
函数小数{
数字=数字;
return+boo?number+0.1:number-0.1.toFixed1;
}
变量输入=$‘输入’;
$“按钮”。单击功能{
var direction=$this.data'direction';
var inputvalue=input.val;
input.valdecimalinputvalue,方向==增加;
};
};
增长
减少
这是有道理的,但我在这里调用。toFixed after和now increase只能工作一次1.0、1.1、1.1和decrease不能工作1.0、0.9、-0.1、-0.1,因为不知什么原因,您将parseFloat更改为使用parseInt。哦,我还以为parseInt是用于将字符串转换为以10为基数的整数。我以为我在简化那里的问题。。哎呀。总之,谢谢。parseInt用于将字符串转换为整数。0.9和1.1不是整数。啊,是的,我错了。整数=整数。嘘我。那么简单的数字是更合适还是更合适呢?
$(function() {
var button = $('button');
button.click(function() {
var button = $(this);
var direction = button.data('direction');
var input = $('input');
var current_value = parseFloat( input.val() ).toFixed(1);
var new_value;
if (direction=='increase') {
new_value = current_value + 0.1;
} else {
new_value = current_value - 0.1;
}
input.val(new_value);
});
});
<button data-direction="1">increase</button>
<button data-direction="-1">decrease</button>
$(function() {
var button = $('button');
var curr_value = 1; // Set it to what you want your starting value to be
button.click(function() {
var button = $(this);
// direction is an integer now: 1 or -1
var direction = parseInt(button.data('direction'));
// Not 'safe' to directly parse it from the input,
// in case someone types in non numeric values.
// Do a check or - even better - make sure non-numeric values can't be
// entered.
var f = $('input');
// check here
var input = parseFloat(f); // input is a number here
// Set the new curr_value
curr_value = curr_value + (input * direction);
input.val(curr_value);
});
});