简体   繁体   中英

Similar jQuery functions to convert temperature; but one of them doesn't work

I'm doing the Weather App project for FreeCodeCamp . I have two similar jQuery functions that convert the temperature from Kelvin to Celcius and Kelvin to Fahrenheit. Here's the link to my CodePen .

When I click the Celcius icon, it converts the value and icon to Fahrenheit; but when I click the Fahrenheit button, it does nothing.

The functions are as follows -

$("#c").click(function() {
  var fahrenheit = ((temp - 273.15) * 9 / 5) + 32;
  $("#temp").html(fahrenheit);
  $("#c").html(" °F");
  $("#c").attr("id", "f");
});

$("#f").click(function() {
  var celcius = temp - 273.15;
  $("#temp").html(celcius);
  $("#f").html(" °C");
  $("#f").attr("id", "c");
});

I tried to debug the code step-by-step by printing the output to the console. I also checked if the id attribute is being changed as well.

What could be going wrong here?

You are changing the id of #c to #f after you click the button. This means that when you are binding the click event to #f there is no element on the page matching the selector.

The standard way to deal with this is to delegate the event from a parent element that is static on the page.

When you delegate, you are binding the event to the parent element and jQuery uses event bubbling to detect the element that you are clicking and using it's own event system will fire events targeting the dynamic element.

$('body').on('click', '#f', function(e) {
  var celcius = temp - 273.15;
  $("#temp").html(celcius);
  $("#f").html(" °C");
  $("#f").attr("id", "c");
});

Using the second argument in the on method you can specify a selector of a child element to delegate to.

The javascript you are running is only being run one time. This means that you are binding the first event handler to #c, and then attempting to bind the second one to #f, but the problem is that when this code runs, #f doesn't exist yet so nothing is bound.

You will need to refactor your code some to get the effect you are looking for. Instead of changing the ID, leave the ID the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM