-4

I want a button to switch between F and C each time i do the click but when i click the button a third time it just doesn't work even though i set back the class to .temp.

$(".temp").click(function() {
  $('#temperature').empty();
  $("#temperature").append(temp.main.temp + " <a class='temper' href='#'>C</a>");

  $(".temper").click(function() {
    $('#temperature').empty();
    $('#temperature').append(data.main.temp +" <a class='temp' href='#'>F</a>");
  });  
});
Chris
  • 31
  • 1
  • 9
  • 1
    Welcome to Stack Overflow! The full content of your question must be **in** your question, not just linked. Links rot, making the question and its answers useless to people in the future, and people shouldn't have to go off-site to help you. Put a [mcve] **in** the question, ideally using Stack Snippets (the `<>` toolbar button) to make it runnable. More: [*How do I ask a good question?*](/help/how-to-ask) – T.J. Crowder Mar 31 '17 at 10:43
  • Possible Duplicate: http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Rajesh Mar 31 '17 at 10:58
  • Thanks! T.J.Crowder for banning me from asking any more questions – Chris Apr 02 '17 at 17:40

4 Answers4

0

I guess you are about to use live jquery event, this can help :

$(document).on("click", ".temp", function() {});
$(document).on("click", ".temper", function() {});
kanzari
  • 87
  • 4
0

Check this Fiddle it's working example but missing this part (temp.main.temp):

$( document ).ready(function() {

$(document).on("click", ".temp", function() {
    $('#temperature').empty();
  $("#temperature").append(" <a class='temper' href='#'>C</a>");
});
$(document).on("click", ".temper", function() {
$('#temperature').empty();
  $("#temperature").append(" <a class='temp' href='#'>F</a>");
  });
});

https://jsfiddle.net/Kanzari/n38xs8sn/2/

kanzari
  • 87
  • 4
-1

In this line:

$("#temperature").append(temp.main.temp + " <a class='temper' href='#'>C</a>");

you are adding some html content dynamically.

So use:

$(document).on('click', '.temper', function(){

});

instead of static listener i.e.

$(".temper").click()

because this kind of listener works for static html only.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
-1

why you wrote the code of temper.click inside the temp.click function? correct it as :

$(".temp").click(function(){

  $('#temperature').empty();
  $("#temperature").append(temp.main.temp+" <a class='temper' href='#'>C</a>");
});


$(".temper").click(function(){

   $('#temperature').empty();
   $('#temperature').append(data.main.temp+" <a class='temp' href='#'>F</a>"  );
});
Arslan Naeem
  • 86
  • 1
  • 8