简体   繁体   中英

Second jQuery button click isn't firing

I am trying to do something ostensibly simple in jsfiddle and it is not working. Essentially I have an h1 html tag with class "me" and a button with class "poo". The first click works and my css color changes, however the second click does not work?

$(".poo").click(function(e){
   e.preventDefault(); 
   $(".me").css("color","green");
   var haha = $("<button>Click Me!!!</button>");
   $(this).after(haha);
   $(haha).addClass("changer");
   $(this).hide();

});
$(".changer").click(function(e){
    e.preventDefault();
   $(".me").css("color","black");
   $(this).hide();
});

The changer click handler is bound before the element exists. Try using the $.on method instead.

http://api.jquery.com/on/

$('body').on('click', '.changer', function() {...})

This works because the event handler is bound to the document body , which already exists on the page. When there is a click anywhere in the body, jQuery will check if the clicked element matches the selector .changer and execute the callback if so.

Alternatively, you could just bind the $('.changer').click event within the first callback.

Bind the second click to the parent element:

$(document).on('click', '.changer', function() {
//function here
});

Update fiddle: http://jsfiddle.net/0yodg7gb/7/

  $(".poo").click(function(e){
       e.preventDefault(); 
       $(".me").css("color","green");
        var haha = $("<button>Click Me!!!</button>").addClass('changer');
        $(this).after(haha);
        $(haha).addClass("changer");
        $(this).hide();
        bindClick();
     });

function bindClick(){
$(".changer").bind('click',function(e){
        e.preventDefault();
       $(".me").css("color","black");
       $(this).hide();
});
}

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