如何在HTML中自动生成数字?



大家好,我只想问如何在 HTML 中自动生成序列号? 我已经找到了答案,但我想从 0001 开始,依此类推。 我试过这个

<button onclick="myFunction()">Try it</button>
<input id="demo" type="text">
<script>
var seq=0;
function myFunction(){
document.getElementById("demo").value = seq;
}
</script>

但它不会输出 000。我会将其保存到数据库中,因此,如果我单击该按钮,它将输出保存在数据库中的下一个数字。请帮帮我谢谢!

如果我理解你的问题,那么有很多方法可以用这种方式格式化数字。也许最简单的如下:

var seq=0;
function myFunction(){
// Increment the value
seq += 1
// The string value that will be displayed
var value = '';
// If sequence is less than 10, prefix with 000
if(seq < 10) {
value = '000' + seq;
}
// If sequence is less than 100, prefix with 00
else if(seq < 100) {
value = '00' + seq;
}
// If sequence is less than 1000, prefix with 0
else if(seq < 1000) {
value = '0' + seq;
}
// Otherwise, just use the value directly
else {
value = seq;
}
// Display the formatted value (ie prefixed with 0's)
document.getElementById("demo").value = value;
}
<button onclick="myFunction()">Try it</button>
<input id="demo" type="text">

此处的一般模式是根据 seq 的值,使用不同数量的"零"字符作为显示的值的前缀。

<!DOCTYPE html>
<html lang="en">
<head>
<title>Index</title>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<input id="demo" type="text">
<script>
var seq = 0;

function myFunction() {
seq = seq +1;
number = '0000'.substr(String(seq).length) + seq
document.getElementById("demo").value = number;
}
</script>
</body>
</html>

var seq = "000" + 0;

就像这样添加,你会在数字之前得到零

var seq = 0;
function myFunction() {
document.getElementById("demo").value = `${++seq}`.padStart(4, '0');
}
<html>
<head></head>
<body>
<button onclick="myFunction()">Try it</button>
<input id="demo" type="text">
</body>
</html>

最新更新