我尝试从简单条件获得布尔返回值。可以使用Eval函数来执行此操作,还是必须使用if语句?
这是我的表达:
alert(eval($("#val1").val() + $("#val2").val() == $("#result1").val()));
它的数值如1 + 1 = 2 // true
答案 0 :(得分:4)
你应该把它们转换成这样的数字:
alert(Number($("#val1").val()) + Number($("#val2").val()) == Number($("#result1").val()));
如果你不将它们转换为数字,java-script假定它们是字符串并进行连接,然后val1(1) + val2(1) = 11
$("#btn").click(function(){
console.log("Converted To Numbers: " + $("#val1").val() + " + " + $("#val2").val() + " = " + (Number($("#val1").val()) + Number($("#val2").val())));
alert(Number($("#val1").val()) + Number($("#val2").val()) == Number($("#result1").val()) );
});
$("#btn2").click(function(){
console.log("No Conversion: " + $("#val1").val() + " + " + $("#val2").val() + " = " + $("#val1").val() + $("#val2").val());
alert($("#val1").val() + $("#val2").val() == $("#result1").val() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="val1">
<input type="text" id="val2">
<input type="text" id="result1">
<br>
<input type="button" id="btn" value="Convert To Numbers">
<input type="button" id="btn2" value="No Conversion">