Js自增函数
js自增函数,可用于唯一值key的赋值。例如:react中,Dom的变化是通过对比相同key值的变化,从而判断是否更新Dom。而key值是唯一值,不能重复的。那么key值应该使用什么样的值合适呢?js自增函数可以成为唯一的key值。
下面使用了两个标签去实现js的自增:
<input>标签
html文件(index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>js自增函数</title>
<style>
body{
text-align:center;
}
.addWrap{
font-size: 30px;
color: black;
width: 200px;
height: 200px;
line-height: 200px;
outline: none;
border: none;
background-color: #ccc;
margin: 0 auto;
cursor:pointer;
padding:0 10px;
}
</style>
<script type="text/javascript">
window.onload = function (){
var addBtn = document.getElementsByTagName("input")[0];
var addValue = 1000;
addBtn.onclick = function (){
addValue++;
var uniqueId = 'id_'+addValue;
addBtn.value = uniqueId;
}
}
</script>
</head>
<body>
<input class='addWrap' type="button" value="id_1000" />
</body>
</html>
<button>标签
html文件(index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>js自增函数</title>
<style>
body{
text-align:center;
}
.addWrap{
font-size: 30px;
color: black;
width: 200px;
height: 200px;
line-height: 200px;
outline: none;
border: none;
background-color: #ccc;
margin: 0 auto;
cursor:pointer;
padding:0 10px;
}
</style>
<script type="text/javascript">
var addValue = 1000;
function uniqueNum(){
addValue++;
var uniqueId = 'id_'+addValue;
var addDom = document.getElementById('addWrap');
addDom.innerHTML = uniqueId;
}
</script>
</head>
<body>
<button id='addWrap' class='addWrap' onclick='uniqueNum()'>id_1000</button>
</body>
</html>