定义和用法
parseInt() 函数可解析一个字符串,并返回一个整数。
实例
在本例中,我们将使用 parseInt() 来解析不同的字符串:
parseInt("10"); //返回 10 parseInt("19",10); //返回 19 (10+9) parseInt("11",2); //返回 3 (10+9) parseInt("17",8); //返回 15 (8+7) parseInt("1f",16); //返回 31 (16+15) parseInt("010"); //未定:返回 10 或 8
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>DOM_test</title>
<script type="text/javascript">
function add1(){
var a=document.getElementById("one");
var b=document.getElementById("two");
var c=document.getElementById("three");
c.value=parseInt(a.value)+parseInt(b.value); //把a.value和b.value中的值转解析成数字
}
</script>
</head>
<body>
<input type="text" id="one"/ size="4">+
<input type="text" id="two" size="4"/>
<input type="button" id="one" value="=" onClick="add1()"/>
<input type="text" id="three" size="4" readyonly/><br/>
<input type="reset" value="reset"/>
</body>
</html>
以下代码用eval函数也可以改为:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>DOM_test</title>
<script type="text/javascript">
function add1(){
var a=eval(document.getElementById("one").value);
var b=eval(document.getElementById("two").value);
var c=document.getElementById("three").value;
alert(eval(a+b));
c=eval(a+b);
document.getElementById("three").value=c;
//c.value=parseInt(a.value)+parseInt(b.value); //把<span style="font-family: Arial, Helvetica, sans-serif;">a.value和b.value中的值转解析成数字</span>
}
</script>
</head>
<body>
<input type="text" id="one"/ size="4">+
<input type="text" id="two" size="4"/>
<input type="button" id="one" value="=" onClick="add1()"/>
<input type="text" id="three" size="4" readyonly/><br/>
<input type="reset" value="reset"/>
</body>
</html>