我的 Javascript 代码有问题。
我有一个从数据库中获取值的 PHP 代码。
示例值是:00027、0208
当我把它放在像
这样的函数中时$id = 00027;
<input type='submit' onclick='CheckPat($id)'>
function CheckPat(x){
alert(x); // returns 23 and for 0208 returns 208
//desired output 00027 and 0208
}
这里的问题是我相信,当我将变量 $id
放入整数值时,它会四舍五入并删除零。我怎样才能返回我想要的值(value)?
最佳答案
$id
是一个数值,但您想要的输出是 $id
值的特殊 String
格式值,因此
您必须对下面的数字进行一些 javascript
方面的计算:
function CheckPat(x) {
x = parseInt(x);
if (x < 10)
alert("0000" + x);
else if (x < 100)
alert("000" + x);
else if (x < 1000)
alert("00" + x);
else if (x < 10000)
alert("0" + x);
else
alert(x);
}
Given value:<input id='val' value="0027" />
<button type='button' onclick='CheckPat(document.getElementById("val").value)'>Check It!</button>
但是如果你想将 $id
值直接转发给 CheckPat
函数,只需将双引号添加到 onclick
事件中,如下所示:
...
<input type='submit' onclick='CheckPat("$id")'>
...
关于JavaScript - 函数中的零值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49503830/