我正在为练习构建一个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>
答案 0 :(得分:0)
您可以使用isNaN()。如果值等于NaN,则此函数返回true。否则返回false。例如:
if(isNaN(document.getElementById("caps").value)){
document.getElementById("caps").value = 0;
}
EDITED
问题是document.getElementById(“caps”)。value返回空字符串
和parceInt(“”)= NaN
所以你可以使用:
function ifInputEmpty(){
if(document.getElementById("caps").value === ""){
return 0;
} else {
return parseInt(document.getElementById("caps").value);
}
}
Fore PlusCaps
function PlusCaps() {
var prevVal = ifInputEmpty();
var nextValue = prevVal + 1;
console.log(nextValue);
setNextValue(nextValue);
}