我有三个带按钮的标签然后点击我需要将值增加1
<script>
function incrementValue() {
var label = document.getElementById('number');
label.textContent = (parseInt(label.textContent, 10) || 0) + 1;
}
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table >
<tr><td><asp:Label ID="lbl1" runat="server" Text="Major"></asp:Label></td><td></td></tr>
<tr><td><asp:Label ID="lbl2" runat="server" Text="1.0"></asp:Label></td><td></td></tr>
<tr><td><asp:Label ID="number" runat="server" Text="0"></asp:Label></td><td></td></tr>
</table>
<input type="button" onclick="incrementValue()" value="click" />
</div>
答案 0 :(得分:1)
使用 textContent
获取和更新标签内的文字内容。然后使用 match()
获取最后一位数字,增加并更新内容。
<script>
function incrementValue() {
var value = parseInt(document.getElementById('number').textContent.match(/\d+$/)[0], 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').textContent = 'major 1.0 ' + value;
}
</script>
<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />
可以更简化
<script>
function incrementValue() {
var label = document.getElementById('number');
label.textContent = 'major 1.0 ' + ((parseInt(label.textContent.match(/\d+$/)[0], 10) || 0) + 1);
}
</script>
<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />
如果字符串变化,你可以做类似的事情
<script>
function incrementValue() {
var label = document.getElementById('number');
var m = label.textContent.match(/^(.*)(\d+)$/);
label.textContent = m[1] + ((parseInt(m[2], 10) || 0) + 1);
}
</script>
<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />
使用您自己的简单三元运算符
<script>
function incrementValue() {
var label = document.getElementById('number');
var m = label.textContent.match(/^(.*?)(\d+)$/);
var value = parseInt(m[2], 10);
value = isNaN(value) ? 0 : value;
label.textContent = m[1] + (value + 1)
}
</script>
<label id="number">major 1.0 0</label>
<input type="button" onclick="incrementValue()" value="Increment Value" />
更新:根据更新后的问题,您可以
<script>
document.onkeyup = KeyCheck;
function KeyCheck(e) {
var key = (window.event) ? event.keyCode : e.keyCode;
if (key == 113) {
var label = document.getElementById('number');
var m = label.textContent.match(/^(.*?)(\d+)$/);
var value = parseInt(m[2], 10);
value = isNaN(value) ? 0 : value;
label.textContent = m[1] + (value + 1)
}
}
</script>
<label id="number">major 1.0 0</label>