Я беру лекцию WebGIS в этом семестре и могу использовать некоторую помощь при отладке моего кода. Это очень простой калькулятор HTML/js, но он дает мне проблемы. Ни одна из кнопок не отображает номера или не выполняет какие-либо функции в моем js-коде. Может ли кто-нибудь дать мне понять, что случилось? Я уверен, что это простое исправление, но конусы в сетчатке горят, пытаясь найти его.
Спасибо!
HTML:
<html>
<head>Calculator!</head>
<body>
<script type="text/javascript" src="calculator.js"></script>
<table>
<tr>
<td colspan="4">
<input type="text" id="txtTotal" name="txtTotal" value="0"/>
</td>
</tr>
<tr>
<td colspan="4">
<input type="text" id="txtTrai" name="txtTrail" disabled='true' value="0"/>
</td>
</tr>
<tr>
<td colspan="4"> </td>
</tr>
<tr>
<td>
<input type="button" id="btnl" name="bnt1" value="1" onclick="nextVal(1);" />
</td>
<td>
<input type="button" id="btn2" name="bnt2" value="2" onclick="nextVal(2);" />
</td>
<td>
<input type="button" id="btn3" name="bnt3" value="3" onclick="nextVal(3);" />
</td>
<td>
</td>
</tr>
<tr>
<td>
<input type="button" id="btn4" name="bnt4" value="4" onclick="nextVal(4);" />
</td>
<td>
<input type="button" id="btn5" name="bnt5" value="5" onclick="nextVal(5);" />
</td>
<td>
<input type="button" id="btn6" name="bnt6" value="6" onclick="nextVal(6);" />
</td>
<td>
</td>
</tr>
<tr>
<td>
<input type="button" id="btn7" name="bnt7" value="7" onclick="nextVal(7);" />
</td>
<td>
<input type="button" id="btn8" name="bnt8" value="8" onclick="nextVal(8);" />
</td>
<td>
<input type="button" id="btn9" name="bnt9" value="9" onclick="nextVal(9);" />
</td>
<td>
<input type="button" id="clear" name="clear" value="C" onclick="clearCalc()" />
</td>
</tr>
<tr>
<td>
<input type="button" id="plus" name="plus" value="+" onclick="setFunction('plus');" />
</td>
<td>
<input type="button" id="btn0" name="btn0" value="0" onclick="nextVal(0);" />
</td>
<td>
<input type="button" id="minus" name="minus" value="-" onclick="setFunction('minus');" />
</td>
<td>
<input type="button" id="equal" name="equal" value="=" onclick="sum();" />
</td>
</tr>
</table>
</body>
</html>
Javascript:
var total = 0;
var funct = '';
function nextVal(1) {
var txtTotal = document.getElementById('txtTotal');
txtTotal.value = 1;
var txtTrail = document.getElementById('txtTrail');
if (funct == 'plus') {
total += 1;
txtTrail.value += ' ' + 1;
}
else if (funct == 'minus'); {
total -= 1;
txtTrail.value += ' ' + 1;
}
else {
total = 1;
txtTrail.value = 1;
}
}
function nextVal(2) {
var txtTotal = document.getElementById('txtTotal');
txtTotal.value = 2;
var txtTrail = document.getElementById('txtTrail');
if (funct == 'plus') {
total += 2;
txtTrail.value += ' ' + 2;
}
else if (funct == 'minus'); {
total -= 2;
txtTrail.value += ' ' + 2;
}
else {
total = 2;
txtTrail.value = 2;
}
}
function nextVal(3) {
var txtTotal = document.getElementById('txtTotal');
txtTotal.value = 3;
var txtTrail = document.getElementById('txtTrail');
if (funct == 'plus') {
total += 3;
txtTrail.value += ' ' + 3;
}
else if (funct == 'minus'); {
total -= 3;
txtTrail.value += ' ' + 3;
}
else {
total = 3;
txtTrail.value = 3;
}
}
function nextVal(4) {
var txtTotal = document.getElementById('txtTotal');
txtTotal.value = 4;
var txtTrail = document.getElementById('txtTrail');
if (funct == 'plus') {
total += 4;
txtTrail.value += ' ' + 4;
}
else if (funct == 'minus'); {
total -= 4;
txtTrail.value += ' ' + 4;
}
else {
total = 4;
txtTrail.value = 4;
}
}
function nextVal(5) {
var txtTotal = document.getElementById('txtTotal');
txtTotal.value = 5;
var txtTrail = document.getElementById('txtTrail');
if (funct == 'plus') {
total += 5;
txtTrail.value += ' ' + 5;
}
else if (funct == 'minus'); {
total -= 5;
txtTrail.value += ' ' + 5;
}
else {
total = 5;
txtTrail.value = 5;
}
}
function nextVal(6) {
var txtTotal = document.getElementById('txtTotal');
txtTotal.value = 6;
var txtTrail = document.getElementById('txtTrail');
if (funct == 'plus') {
total += 6;
txtTrail.value += ' ' + 6;
}
else if (funct == 'minus'); {
total -= 6;
txtTrail.value += ' ' + 6;
}
else {
total = 6;
txtTrail.value = 6;
}
}
function nextVal(7) {
var txtTotal = document.getElementById('txtTotal');
txtTotal.value = 7;
var txtTrail = document.getElementById('txtTrail');
if (funct == 'plus') {
total += 7;
txtTrail.value += ' ' + 7;
}
else if (funct == 'minus'); {
total -= 7;
txtTrail.value += ' ' + 7;
}
else {
total = 7;
txtTrail.value = 7;
}
}
function nextVal(8) {
var txtTotal = document.getElementById('txtTotal');
txtTotal.value = 8;
var txtTrail = document.getElementById('txtTrail');
if (funct == 'plus') {
total += 8;
txtTrail.value += ' ' + 8;
}
else if (funct == 'minus'); {
total -= 8;
txtTrail.value += ' ' + 8;
}
else {
total = 8;
txtTrail.value = 8;
}
}
function nextVal(9) {
var txtTotal = document.getElementById('txtTotal');
txtTotal.value = 9;
var txtTrail = document.getElementById('txtTrail');
if (funct == 'plus') {
total += 9;
txtTrail.value += ' ' + 9;
}
else if (funct == 'minus'); {
total -= 9;
txtTrail.value += ' ' + 9;
}
else {
total = 9;
txtTrail.value = 9;
}
}
function nextVal(0) {
var txtTotal = document.getElementById('txtTotal');
txtTotal.value = 0;
var txtTrail = document.getElementById('txtTrail');
if (funct == 'plus') {
total += 0;
txtTrail.value += ' ' + 0;
}
else if (funct == 'minus'); {
total -= 0;
txtTrail.value += ' ' + 0;
}
else {
total = 0;
txtTrail.value = 0;
}
}
function setFunction(f) {
var txtTrail = document.getElementById('txtTrail');
funct = f;
if (funct == 'true') {
txt.Trail.value += ' +';
}
else if (funct == 'minus') {
txt.Trail.value -= ' -';
}
}
function sum() {
var txtTotal = document.getElementById('txtTotal');
if (txtTotal) {
txtTotal.value = total;
}
function clearCalc() {
var txtTotal = document.getElementById('txtTotal');
txtTotal.value = 0;
var txtTrail =document.getElementById('txtTrail');
txtTotal.value = 0;
total = 0;
funct = '';
}
Могу ли я сделать несколько рекомендаций?
У вас должен быть один JS-метод, который захватывает все входные значения из калькулятора. Я буду распространять события здесь, установите обработчик onclick на родительский элемент вместо каждого элемента. В этом методе посмотрите на цель и добавьте на дисплей. Это лучший и более чистый подход, а затем добавление встроенных обработчиков onclick с заданным параметром.
Также вам не нужно иметь уникальную функцию nextVal для каждого ключа. Просто передайте это как параметр или установите значение attr для данных на ключ и получите значение в вашем одиночном обработчике.
Подключите этот обработчик событий, привязав его к одному классу. Назначьте каждую клавишу в тот же класс (например, значение ввода). Если вы решите не использовать распространение событий - вы также можете привязать обработчик onclick к каждому элементу этого класса.
В настоящее время большая проблема заключается в том, что вы не можете иметь несколько функций с тем же именем:
// This makes no sense
function nextVal(1) { ... }
function nextVal(2) { ... }
// ...
Вы можете изменить его на это:
function nextVal1() { ... }
function nextVal2() { ... }
// ...
Есть много других вещей, которые можно было бы сделать с этим кодом, как отметил Ньюс, но начните с этого...
Вторая проблема - это (многие) строки, подобные этому:
else if (funct == 'minus'); {
// ^
// this semicolon |
// doesn't belong -----+
Эта точка с запятой завершает утверждение, и, следовательно, раздел { }
разделителями не действует так, как вы ожидаете.
Также существует недостающая конечная скобка для функции sum
, и, наконец, идентификатор элемента txtTrail
имеет орфографическую ошибку. Фиксация всех этих, я думаю, приведет вас в рабочее состояние.
Но пункты Newse делают в его ответе, и аналогично те, которые в akinuri Fiddle очень важны в развитии ваших навыков программирования.
Этот код чрезвычайно повторяется. Одним из важных максим программирования, чтобы сохранить ваш код DRY - D on't R EPEAT Y, себя. Существует несколько простых методов, которые помогут удалить повторение в этом коде.
Кроме того, многие возражали бы по аналогичной причине нескольким обработчикам событий, которые вы прикрепляете. Существуют такие методы, как делегирование событий, которые помогут очистить это.
Некоторые из этих методов придут, конечно, во время программирования времени. Но лучший способ ускорить их - держать постоянный критический взгляд на вашу собственную работу, всегда спрашивая себя: "Как я мог сделать это лучше?"
Вышеупомянутый Fiddle - это не код, которым гордился продвинутый разработчик. Но это сработало. Итак, мой вызов для вас сейчас: что вы можете сделать, чтобы улучшить его?