【发布时间】:2018-02-06 09:42:45
【问题描述】:
我正在为练习构建一个 PhoneGap 应用程序,这意味着我希望不惜一切代价避免使用 jQuery,不接受任何参数。我有一个带有工作按钮的输入类型,但是如果用户删除了所有留下空白输入字段的数字,然后按下加号或减号按钮,它会在输入框“Nan”中报告。如何将其设置为“0”?
window.onload = function() {
var CapsNum = localStorage.getItem("CapsNum");
if (CapsNum == null) {
setCapsNum = "0";
} else {
document.getElementById("caps").value = CapsNum;
}
}
window.onbeforeunload = function() {
localStorage.setItem("CapsNum", document.getElementById("caps").value);
}
function PlusCaps() {
var nextValue = parseInt(document.getElementById("caps").value) + 1;
console.log(nextValue);
setNextValue(nextValue);
}
function MinusCaps() {
var nextValue = parseInt(document.getElementById("caps").value) - 1;
// If the next value is valid...
if (nextValue >=0) {
// Set the next value.
setNextValue(nextValue);
}
}
function setNextValue(nextValue) {
localStorage.setItem("CapsNum", nextValue);
document.getElementById("caps").value = nextValue;
}
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
.button {
font-size: 18px;
display: inline-block;
width: 50px;
height: 50px;
margin-top: 10px;
margin-bottom: 10px;
line-height: 20px;
vertical-align: top;
outline: none;
cursor: pointer;
border: 1px solid rgba(80, 80, 80, 1);
-moz-border-radius: 8px;
-webkit-border-radius: 3px;
border-radius: 4px;
}
#caps {
margin-top:12px;
margin-bottom: 12px;
font-size: 35px;
width: 60px;
text-align: center;
background: TRANSPARENT;
color: YELLOW;
border: 2px solid;
outline: none;
}
<div id="CapsButton" tabindex="1">
<input type="button" id="minus" class="button" value="-" style="margin-right:10px" onclick="MinusCaps()" />
<input type="tel" id="caps" maxlength="3" size="3" pattern="[0-9]+" value="" autocomplete="off" onkeypress="return isNumberKey(event)" />
<input type="button" id="plus" class="button" value="+" style="margin-left:10px" onclick="PlusCaps()" /></div>
【问题讨论】:
标签: javascript css html numbers phonegap