我可以在if
语句中插入else
语句吗?
代码:
function swicthNum() {
'use strict';
var processDoc = document.getElementById('process').innerHTML;
if (processDoc == 'Dollars to Algerian Dinar') {
processDoc = 'Algerian Dinar to Dollars';
} else {
processDoc = 'Dollars to Algerian Dinar';
}
return processDoc;
}
function moneyCalc() {
'use strict';
var num = document.getElementById('moneyNum').value,
lastResultDoc = document.getElementById('lastResult'),
result = num * 107.39,
lastResult = document.getElementById('lastResult');
if (num < 0) {
lastResult.innerHTML = 'The process don\'t accept negative numbers';
} else {
if (processDoc == 'Dollars to Algerian Dinar') {
lastResult.innerHTML = result;
} else {
result = num * 0.0093;
lastResult.innerHTML = result;
}
}
}
&#13;
<p id="process">
Dollars to Algerian Dinar
</p>
<button onclick="swicthNum()">Switch!</button>
<br />
<form action="AdvancedFunction.html" method="post">
<input id="moneyNum" name="" type="number" value="" />
<input onclick="moneyCalc()" name="" type="submit" value="Calculate" />
</form>
<div id="lastResult">Result</div>
&#13;
答案 0 :(得分:1)
你绝对可以,但在你的情况下,你可以简单地去:
if (num < 0) {
lastResult.innerHTML = 'The process don\'t accept negative numbers';
}
else if (processDoc == 'Dollars to Euro') {
lastResult.innerHTML = result;
}
else {
result = num * 0.0093;
lastResult.innerHTML = result;
}
阅读可能更简单。
return false;
。
function swicthNum() {
'use strict';
window.processDoc = document.getElementById('process').innerHTML;
if (window.processDoc.indexOf('Dollars to Algerian Dinar')>-1) {
window.processDoc = 'Algerian Dinar to Dollars';
} else {
window.processDoc = 'Dollars to Algerian Dinar';
}
document.getElementById('process').innerHTML = window.processDoc;
return window.processDoc;
}
function moneyCalc() {
'use strict';
var num = document.getElementById('moneyNum').value,
lastResultDoc = document.getElementById('lastResult'),
result = num * 107.39,
lastResult = document.getElementById('lastResult');
if (num < 0) {
lastResult.innerHTML = 'The process don\'t accept negative numbers';
} else {
if (window.processDoc == 'Dollars to Algerian Dinar') {
lastResult.innerHTML = result;
} else {
result = num * 0.0093;
lastResult.innerHTML = result;
}
}
}
<p id="process">Dollars to Algerian Dinar</p>
<button onclick="swicthNum()">Switch!</button>
<br />
<form action="#" method="post">
<input id="moneyNum" name="" type="number" value="" />
<input onclick="moneyCalc(); return false;" name="" type="submit" value="Calculate" />
</form>
<div id="lastResult">Result</div>