Как исправить код, в котором выполняется только одна часть функции?

#javascript #html #css

Вопрос:

Я пытаюсь создать веб-сайт по преобразованию температуры super super basic, который преобразует Фаренгейт в Цельсий, Цельсий в Фаренгейт и Кельвин в Цельсий, я, вероятно, добавлю дополнительные опции позже. Код, похоже, возвращает только значение по Фаренгейту. Я думаю, что он получает ввод, но запускает неправильную часть функции?? Любая помощь была бы потрясающей

 // Shows Dropdown menu
function show() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i  ) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
// Changes dropdown button text to the option

function celciusText() {
  document.getElementById("dropdown").innerHTML = 'Celcius ▼';
}

function fahrenheitText() {
  document.getElementById("dropdown").innerHTML = 'Fahrenheit ▼';
}

function kelvinText() {
  document.getElementById("dropdown").innerHTML = 'Kelvin ▼';
}

// Conversion Script  
function tempConvert() {
  let input = document.getElementById("tempInput").value

  if (document.getElementById("dropdown").value = 'Celcius ▼') {
    let output = (input * (9 / 5)   32)

    document.getElementById("tempOutput").innerHTML = output   " F";

  } else if (document.getElementById("dropdown").value = 'Fahrenheit ▼') {
    let output = (input - 32) * (5 / 9)

    document.getElementById("tempOutput").innerHTML = output   " C";
  } else if (document.getElementById("dropdown").value = 'Kelvin ▼') {
    let output = (input   273.15)

    document.getElementById("tempOutput").innerHTML = output   " C";
  } else {
    window.prompt("Invalid")
  }
};

// Reset Button 
function clearFields() {
  const clearBtn = document.getElementById("reset");
  const inputField = document.getElementById("tempInput");
  const outputField = document.getElementById("tempOutput");
  const dropDown = document.getElementById("dropdown")



  clearBtn.addEventListener('click', () => {
    inputField.value = " ";
    outputField.value = " ";
    dropDown.innerHTML = "Temperature Unit ▼";
  })
} 
 /* Dropdown Button */

.dropbtn {
  display: inline-block;
  padding: 10px 14px;
  color: #3485e4;
  border: 1px solid #2d71be;
  text-decoration: none;
  font-size: 14px;
  transform: translate(0px, 65px);
  line-height: 120%;
  background-color: rgba(255, 255, 255, 0);
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  -webkit-transition: background-color 300ms ease;
  -moz-transition: background-color 300ms ease;
  transition: background-color 300ms ease;
  cursor: pointer;
}


/* Dropdown button on hover amp; focus */

.dropbtn:hover,
.dropbtn:focus {
  background-color: rgba(174, 221, 245, 0.3);
  color: #3485e4;
}


/* The container <div> - needed to position the dropdown content */

.dropdown {
  position: relative;
  display: inline-block;
}


/* Dropdown Content (Hidden by Default) */

.dropdown-content {
  display: none;
  position: absolute;
  background-color: rgba(255, 255, 255, 0);
  width: 145px;
  z-index: 1;
}


/* Links inside the dropdown */

.dropdown-content button {
  display: inline-block;
  transform: translate(0px, 45px);
  padding: 10px 14px;
  width: 145px;
  color: #3485e4;
  border: 1px solid #2d71be;
  text-decoration: none;
  font-size: 14px;
  line-height: 120%;
  background-color: rgba(255, 255, 255, 0);
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  -webkit-transition: background-color 300ms ease;
  -moz-transition: background-color 300ms ease;
  transition: background-color 300ms ease;
  cursor: pointer;
}


/* Change color of dropdown links on hover */

.dropdown-content button:hover {
  background-color: #ddd
}


/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */

.show {
  display: block;
}


/* CSS for number input */

input[type=number] {
  display: inline-block;
  width: 50%;
  padding: 12px 20px;
  transform: translate(150px);
  margin: 8px 0;
  box-sizing: border-box;
  z-index: 1;
}


/* CSS for submit button */

input[type=button] {
  transition-duration: 0.4s;
  border: 2px solid lightseagreen;
  border-radius: 5px;
  background-color: rgba(255, 255, 255, 0);
  ;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
  text-decoration: none;
  display: inline-block;
  width: 85px;
  padding: 5px 6px;
  margin: auto;
  box-sizing: border-box;
  cursor: pointer;
}

input[type=button]:hover {
  background-color: lightseagreen;
  color: white;
}


/* Output Field */

output {
  display: inline;
  width: 100%;
  padding: 10px 100px;
  margin: auto;
  border: 1px solid black;
}


/* Reset Button */

#reset {
  transition-duration: 0.4s;
  border: 2px solid rgb(178, 32, 56);
  border-radius: 5px;
  background-color: rgba(178, 255, 255, 0);
  ;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
  text-decoration: none;
  display: inline-block;
  width: 85px;
  padding: 5px 6px;
  margin: auto;
  box-sizing: border-box;
  cursor: pointer;
}

#reset:hover {
  background-color: rgb(178, 32, 56);
  color: white;
}

#small {
  font-size: 11px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  position: absolute;
  transform: translate(150px, 10px)
} 
 <!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<div id="inputForm">
  <form id="input">
    <div>
      <a href="#" onclick="show()" id="dropdown" class="dropbtn">Temperature Unit ▼</a>
      <div id="myDropdown" class="dropdown-content">
        <button onclick=celciusText() id="celcius" href="#" type="button">Celcius</button>
        <button id="fahrenheit" onclick=fahrenheitText() type="button">Fahrenheit</button>
        <button type="button" id="Kelvin" onclick=kelvinText()>Kelvin</button>
      </div>
    </div>
    <div>
      <label id="small" for="tempInput">Input Temperature:</label> <br>
      <input type="number" id="tempInput" name="tempInput"> </br>
    </div>
    <input type="button" value="Submit" onclick=tempConvert()>
    <input type="button" id="reset" value="Reset" onclick=clearFields()>
    <output name="tempOutput" for="tempInput" id="tempOutput">
  </div>

</form>
  <body>
  <script src="script.js"></script>
  </body>
</html> 

Комментарии:

1. if (document.getElementById("dropdown").value = Celsius ▼') — сравнение выполняется с использованием == или === , назначение =

Ответ №1:

Здесь две проблемы :-

  • Вы присваиваете значения вместо проверок на равенство, т. е. вы проводите сравнение через = , а не == / === .
  • В элементе нет никакого value свойства dropdown . Вам нужно использовать textContent .

Вот ваш измененный фрагмент :-

 // Shows Dropdown menu
function show() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i  ) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
// Changes dropdown button text to the option

function celciusText() {
  document.getElementById("dropdown").innerHTML = 'Celcius ▼';
}

function fahrenheitText() {
  document.getElementById("dropdown").innerHTML = 'Fahrenheit ▼';
}

function kelvinText() {
  document.getElementById("dropdown").innerHTML = 'Kelvin ▼';
}

// Conversion Script  
function tempConvert() {
  let input = document.getElementById("tempInput").value
  let dropdownValue = document.getElementById("dropdown").textContent;
  if (dropdownValue === 'Celcius ▼') {
    let output = (input * (9 / 5)   32)

    document.getElementById("tempOutput").innerHTML = output   " F";

  } else if (dropdownValue === 'Fahrenheit ▼') {
    let output = (input - 32) * (5 / 9)

    document.getElementById("tempOutput").innerHTML = output   " C";
  } else if (dropdownValue === 'Kelvin ▼') {
    let output = (input   273.15)

    document.getElementById("tempOutput").innerHTML = output   " C";
  } else {
    window.prompt("Invalid")
  }
};

// Reset Button 
function clearFields() {
  const clearBtn = document.getElementById("reset");
  const inputField = document.getElementById("tempInput");
  const outputField = document.getElementById("tempOutput");
  const dropDown = document.getElementById("dropdown")



  clearBtn.addEventListener('click', () => {
    inputField.value = " ";
    outputField.value = " ";
    dropDown.innerHTML = "Temperature Unit ▼";
  })
} 
 /* Dropdown Button */

.dropbtn {
  display: inline-block;
  padding: 10px 14px;
  color: #3485e4;
  border: 1px solid #2d71be;
  text-decoration: none;
  font-size: 14px;
  transform: translate(0px, 65px);
  line-height: 120%;
  background-color: rgba(255, 255, 255, 0);
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  -webkit-transition: background-color 300ms ease;
  -moz-transition: background-color 300ms ease;
  transition: background-color 300ms ease;
  cursor: pointer;
}


/* Dropdown button on hover amp; focus */

.dropbtn:hover,
.dropbtn:focus {
  background-color: rgba(174, 221, 245, 0.3);
  color: #3485e4;
}


/* The container <div> - needed to position the dropdown content */

.dropdown {
  position: relative;
  display: inline-block;
}


/* Dropdown Content (Hidden by Default) */

.dropdown-content {
  display: none;
  position: absolute;
  background-color: rgba(255, 255, 255, 0);
  width: 145px;
  z-index: 1;
}


/* Links inside the dropdown */

.dropdown-content button {
  display: inline-block;
  transform: translate(0px, 45px);
  padding: 10px 14px;
  width: 145px;
  color: #3485e4;
  border: 1px solid #2d71be;
  text-decoration: none;
  font-size: 14px;
  line-height: 120%;
  background-color: rgba(255, 255, 255, 0);
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  -webkit-transition: background-color 300ms ease;
  -moz-transition: background-color 300ms ease;
  transition: background-color 300ms ease;
  cursor: pointer;
}


/* Change color of dropdown links on hover */

.dropdown-content button:hover {
  background-color: #ddd
}


/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */

.show {
  display: block;
}


/* CSS for number input */

input[type=number] {
  display: inline-block;
  width: 50%;
  padding: 12px 20px;
  transform: translate(150px);
  margin: 8px 0;
  box-sizing: border-box;
  z-index: 1;
}


/* CSS for submit button */

input[type=button] {
  transition-duration: 0.4s;
  border: 2px solid lightseagreen;
  border-radius: 5px;
  background-color: rgba(255, 255, 255, 0);
  ;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
  text-decoration: none;
  display: inline-block;
  width: 85px;
  padding: 5px 6px;
  margin: auto;
  box-sizing: border-box;
  cursor: pointer;
}

input[type=button]:hover {
  background-color: lightseagreen;
  color: white;
}


/* Output Field */

output {
  display: inline;
  width: 100%;
  padding: 10px 100px;
  margin: auto;
  border: 1px solid black;
}


/* Reset Button */

#reset {
  transition-duration: 0.4s;
  border: 2px solid rgb(178, 32, 56);
  border-radius: 5px;
  background-color: rgba(178, 255, 255, 0);
  ;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
  text-decoration: none;
  display: inline-block;
  width: 85px;
  padding: 5px 6px;
  margin: auto;
  box-sizing: border-box;
  cursor: pointer;
}

#reset:hover {
  background-color: rgb(178, 32, 56);
  color: white;
}

#small {
  font-size: 11px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  position: absolute;
  transform: translate(150px, 10px)
} 
 <!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<div id="inputForm">
  <form id="input">
    <div>
      <a href="#" onclick="show()" id="dropdown" class="dropbtn">Temperature Unit ▼</a>
      <div id="myDropdown" class="dropdown-content">
        <button onclick=celciusText() id="celcius" href="#" type="button">Celcius</button>
        <button id="fahrenheit" onclick=fahrenheitText() type="button">Fahrenheit</button>
        <button type="button" id="Kelvin" onclick=kelvinText()>Kelvin</button>
      </div>
    </div>
    <div>
      <label id="small" for="tempInput">Input Temperature:</label> <br>
      <input type="number" id="tempInput" name="tempInput"> </br>
    </div>
    <input type="button" value="Submit" onclick=tempConvert()>
    <input type="button" id="reset" value="Reset" onclick=clearFields()>
    <output name="tempOutput" for="tempInput" id="tempOutput">
  </div>

</form>
  <body>
  <script src="script.js"></script>
  </body>
</html> 

Ответ №2:

  1. У вас добавлены неправильные расчеты.
  2. Кроме того, вы присваиваете значение вместо сравнения значения в каждой проверке if

Предложение: Измерьте температуру в одной единице измерения, а затем преобразуйте в любую другую. См., например, мой фрагмент.

 // Shows Dropdown menu
function show() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i  ) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
// Changes dropdown button text to the option

function celciusText() {
  document.getElementById("dropdown").innerHTML = 'Celcius ▼';
  document.getElementById("unit").value = 'celcius';
}

function fahrenheitText() {
  document.getElementById("dropdown").innerHTML = 'Fahrenheit ▼';
  document.getElementById("unit").value = 'fahrenheit';
}

function kelvinText() {
  document.getElementById("dropdown").innerHTML = 'Kelvin ▼';
  document.getElementById("unit").value = 'kelvin';
}

// Conversion Script  
function tempConvert() {
  let input = document.getElementById("tempInput").value

  if (document.getElementById("unit").value == 'celcius') {
    let output = input;
 console.log('C ' output);
    document.getElementById("tempOutput").innerHTML = output   " C";

  } else if (document.getElementById("unit").value == 'fahrenheit') {
    let output = (9/5 *input   32);
console.log(input   ' >F '  output);
    document.getElementById("tempOutput").innerHTML = output   " F";
  } else if (document.getElementById("unit").value == 'kelvin') {
    let output = parseFloat(parseFloat(input)   273.15);
console.log(input   'K ' output);
    document.getElementById("tempOutput").innerHTML = output   " K";
  } else {
    window.prompt("Invalid")
  }
};

// Reset Button 
function clearFields() {
  const clearBtn = document.getElementById("reset");
  const inputField = document.getElementById("tempInput");
  const outputField = document.getElementById("tempOutput");
  const dropDown = document.getElementById("dropdown")



  clearBtn.addEventListener('click', () => {
    inputField.value = " ";
    outputField.value = " ";
    dropDown.innerHTML = "Temperature Unit ▼";
  })
} 
 /* Dropdown Button */

.dropbtn {
  display: inline-block;
  padding: 10px 14px;
  color: #3485e4;
  border: 1px solid #2d71be;
  text-decoration: none;
  font-size: 14px;
  transform: translate(0px, 65px);
  line-height: 120%;
  background-color: rgba(255, 255, 255, 0);
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  -webkit-transition: background-color 300ms ease;
  -moz-transition: background-color 300ms ease;
  transition: background-color 300ms ease;
  cursor: pointer;
}


/* Dropdown button on hover amp; focus */

.dropbtn:hover,
.dropbtn:focus {
  background-color: rgba(174, 221, 245, 0.3);
  color: #3485e4;
}


/* The container <div> - needed to position the dropdown content */

.dropdown {
  position: relative;
  display: inline-block;
}


/* Dropdown Content (Hidden by Default) */

.dropdown-content {
  display: none;
  position: absolute;
  background-color: rgba(255, 255, 255, 0);
  width: 145px;
  z-index: 1;
}


/* Links inside the dropdown */

.dropdown-content button {
  display: inline-block;
  transform: translate(0px, 45px);
  padding: 10px 14px;
  width: 145px;
  color: #3485e4;
  border: 1px solid #2d71be;
  text-decoration: none;
  font-size: 14px;
  line-height: 120%;
  background-color: rgba(255, 255, 255, 0);
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  -webkit-transition: background-color 300ms ease;
  -moz-transition: background-color 300ms ease;
  transition: background-color 300ms ease;
  cursor: pointer;
}


/* Change color of dropdown links on hover */

.dropdown-content button:hover {
  background-color: #ddd
}


/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */

.show {
  display: block;
}


/* CSS for number input */

input[type=number] {
  display: inline-block;
  width: 50%;
  padding: 12px 20px;
  transform: translate(150px);
  margin: 8px 0;
  box-sizing: border-box;
  z-index: 1;
}


/* CSS for submit button */

input[type=button] {
  transition-duration: 0.4s;
  border: 2px solid lightseagreen;
  border-radius: 5px;
  background-color: rgba(255, 255, 255, 0);
  ;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
  text-decoration: none;
  display: inline-block;
  width: 85px;
  padding: 5px 6px;
  margin: auto;
  box-sizing: border-box;
  cursor: pointer;
}

input[type=button]:hover {
  background-color: lightseagreen;
  color: white;
}


/* Output Field */

output {
  display: inline;
  width: 100%;
  padding: 10px 100px;
  margin: auto;
  border: 1px solid black;
}


/* Reset Button */

#reset {
  transition-duration: 0.4s;
  border: 2px solid rgb(178, 32, 56);
  border-radius: 5px;
  background-color: rgba(178, 255, 255, 0);
  ;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
  text-decoration: none;
  display: inline-block;
  width: 85px;
  padding: 5px 6px;
  margin: auto;
  box-sizing: border-box;
  cursor: pointer;
}

#reset:hover {
  background-color: rgb(178, 32, 56);
  color: white;
}

#small {
  font-size: 11px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  position: absolute;
  transform: translate(150px, 10px)
} 
 <!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<div id="inputForm">
  <form id="input">
    <div>
    
      <a href="#" onclick="show()" id="dropdown" class="dropbtn">Temperature Unit ▼</a>
      <div id="myDropdown" class="dropdown-content">
        <button onclick="celciusText()" id="celcius"type="button">Celcius</button>
        <button onclick="fahrenheitText()" id="fahrenheit" type="button">Fahrenheit</button>
        <button onclick="kelvinText()" type="button" id="Kelvin" >Kelvin</button>
      </div>
      <input type="hidden" name="unit" id="unit" />
    </div>
    <div>
      <label id="small" for="tempInput">Input Temperature in Celcius:</label> <br>
      <input type="number" id="tempInput" name="tempInput"> </br>
    </div>
    <input type="button" value="Submit" onclick=tempConvert()>
    <input type="button" id="reset" value="Reset" onclick=clearFields()>
    <output name="tempOutput" for="tempInput" id="tempOutput">
  </div>

</form>
  <body>
  <script src="script.js"></script>
  </body>
</html> 

Комментарии:

1. Этот фрагмент возвращает правильные результаты и выполнен лучшим образом.