gpt4 book ai didi

javascript - jQuery 始终将文本输入解析为字符串 - 如何将 val 检索为 int 或 float?

转载 作者:搜寻专家 更新时间:2023-10-31 23:00:24 24 4
gpt4 key购买 nike

我正在根据两个文本输入的值进行一些计算。值可以是 float 或整数。计算在 keyup 事件上触发。

所以目前我必须评估 val 以确定它是 float 还是 int,然后根据需要使用 parseIntparseFloat

这似乎有点老套或矫枉过正。有更好的方法吗?

这里有一个 fiddle 来演示:https://jsfiddle.net/2hw0tnhb/

HTML:

<label id="x-label" for="x">Float</label>
<br/>
<input type="text" name="x" id="x" value="29.7" class="axis"/>

<br/>
<br/>

<label id="y-label" for="y">Int</label>
<br/>
<input type="text" name="y" id="y" value="21" class="axis"/>

JS:

var $x = $('#x');
var $y = $('#y');
var $axis = $('.axis');
var x_label = $('#x-label');
var y_label = $('#y-label');

$axis.keyup(function(){

var $this = $(this);
var val = $this.val();
var axis = 'x';

if($this.attr('id') === 'y') axis = 'y';

//check if int or float:
if(parseFloat(val) > Math.floor(parseFloat(val))){
//it is a float - use parseFloat()
if( axis === 'x' ){
x_label.text('Float');
}else{
y_label.text('Float');
}
}
else{
//it is an int - use parseInt()
if( axis === 'x' ){
x_label.text('Int');
}else{
y_label.text('Int');
}
}
});

最佳答案

您可以使用前导+,结果将是数字、整数或 float :

var val = +$this.val(); //or +this.value

并且您可以使用 type="number" 将条目保存到 .axis 数字中:

<input type="number" name="x" id="x" value="29.7" class="axis"/>

$(function() {
var $x = $('#x');
var $y = $('#y');
var $axis = $('.axis');
var x_label = $('#x-label');
var y_label = $('#y-label');

$axis.keyup(function(){

var $this = $(this);
var val = +$this.val();
var axis = this.name;

console.log( val );
console.log( val + 3.5 );
console.log( val + 4 );
})
.trigger('keyup');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label id="x-label" for="x">Float</label>
<br/>
<input type="number" name="x" id="x" value="29.7" class="axis"/>

<br/>
<br/>

<label id="y-label" for="y">Int</label>
<br/>
<input type="number" name="y" id="y" value="21" class="axis"/>

Unary plus (+)
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

引用:Arithmetic Operators

关于javascript - jQuery 始终将文本输入解析为字符串 - 如何将 val 检索为 int 或 float?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32035194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com