我有三个带有按钮的标签,但是点击我需要将值增加 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>
最佳答案
使用 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>
关于javascript - 使用javascript单击按钮将标签值增加一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37497314/