我正在尝试编写一个仅选择较大数字的小程序。我的问题是它希望我在.js文件中使用if else语句。这是我的HTML。
<body>
BOX 1<input id = 'box1' name = '' value = '' class = ''><br>
BOX 2<input id = 'box2' name = '' value = '' class = ''><br>
BIGGER<input id = 'bigger' name = '' value = '' class = ''><br>
<button id = 'go' class = ''>GO</button>
<script src = 'js/javascript 03.js'></script>
</body>
我真的很难写.js文件。
document.getElementById('go').onclick = function() {
var box1 = document.getElementById('box1').value;
number1 = parseFloat(number1);
var box2 = document.getElementById('box2').value;
number2 = parseFloat(number2);
var bigger =
document.getElementById('bigger').value = total;
if (number1 > number2) {
bigger = number1;
};
else {
bigger = number2;
}
};
最佳答案
首先,我建议您避免在属性和参数之间留空格。尽管它似乎可以正常工作,但我从未见过这样的HTML代码。
这是我想出的:
<html>
<body>
BOX 1 <input id='box1' name='' value='' class=''><br>
BOX 2 <input id='box2' name='' value='' class=''><br>
BIGGER<input id='bigger' name='' value='' class=''><br>
<button id='go' class=''> GO</button>
<script type="text/javascript">
document.getElementById('go').onclick = function() {
// Let's get the values and convert them to integers
var val1 = parseInt(document.getElementById('box1').value);
var val2 = parseInt(document.getElementById('box2').value);
// Let's pick the bigger one and put it in another variable, "bigger"
if (val1 > val2)
var bigger = val1;
else
var bigger = val2;
// Let's write the value we just picked to the field whose id is "bigger"
document.getElementById('bigger').value = bigger;
}
</script>
</body>
</html>