执行串联而不是附加javascript [英] performs concatenation instead of addition javascript

查看:74
本文介绍了执行串联而不是附加javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的脚本.

<script>
function myFunction()
{
var y=$("#text").val();
var z=10;
var x=y+z;
var demoP=document.getElementById("demo")
demoP.innerHTML="x=" + x;
}
</script>

它读取文本字段的值并添加一个值.但是它执行级联而不是加法.我该如何解决这个问题.

It reads the value of a text-field and add with a value. But it performs concatenation instead of addition. How can I solve this problem.??

推荐答案

此行:

var y=$("#text").val();

返回一个字符串.

您需要执行的操作是使用以下方法之一将该结果转换/强制转换为数字:

What you need to do is convert/coerce this result to a number using one of the following methods:

var y = parseInt($("#text").val(), 10);

var y = parseFloat($("#text").val()); //  returns a floating point number

var y = Number($("#text").val());

var y = +$("#text").val();

这篇关于执行串联而不是附加javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆