gpt4 book ai didi

javascript - jQuery 执行数学运算

转载 作者:行者123 更新时间:2023-12-03 03:10:38 25 4
gpt4 key购买 nike

HTML 用户输入:

=110*200

jQuery:

   $(document).on("change", ".calculator", function(){
var value = $(this).val();
if(value.charAt(0) == '='){
var newval = value.slice(1);
console.log(parseInt(newval));
}
})

输出:

110

谁能告诉我如何使用这个程序进行数学运算?我哪里出错了,为什么它不起作用?

最佳答案

发生这种情况是因为您从未评估表达式本身。您将字符串表达式转换为整数,它从表达式中获取可识别的整数部分,并在 * 字符处将其断开。

Evaluate your expression with eval, and it will get calculated. Alternatively, you can also use Function construct as described in answer here to evaluate this expression.

$(document).on("change", ".calculator", function(){
var value = $(this).val();
console.log(value.charAt(0));
if(value.charAt(0) == '='){
var newval = value.slice(1);
console.log(parseInt(eval(newval)));
console.log(new Function('return ' + newval)());
}
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="calculator" type="text">

关于javascript - jQuery 执行数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46967627/

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