我正在尝试编写一个只选择较大数字的小程序。我的问题是它要我在.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;
}
};
答案 0 :(得分:1)
首先,我建议您避免使用属性和参数之间的空格。虽然它看起来一直都是一样的,但我从来没有见过这样的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>