<button id="first">Click me first</button>
$('#first').click(function(){
$('body').append('<button id="second">Now click me</button>');
});
$('#second').click(function(){
$(this).hide();
});
When #first
is clicked, #second
gets appended. When #second
gets clicked, I want it to hide itself.
Why isn't this working?
When you initiate this event handler
$('#second').click(function(){
$(this).hide();
});
'#second' element doesn't exist yet. Later you add the element but that element doesn't initiated with any event handler.
You can try this
$('#first').click(function(){
$('body').append('<button id="second">Now click me</button>');
// event handler will attached for already exist '#second' element
// attach event if only #second doesn't have event yet
if(!($('#second').data('events') != null && $('#second').data('events').click != undefined && $('#second').data('events').click.length == 1))
$('#second').click(function(){
$(this).hide();
});
});
Use jQuery on
function.
$(document).on('click', '#second', function(){
$(this).hide();
});
It's not working because $('#second')
does not match anything when it gets executed.
Try assigning the click handler to the element before adding to the DOM:
$('#first').click(function(){
var $button = $('<button id="second">Now click me</button>');
$button.click(function() {
// handler
});
$('body').append($button);
});
You can also use on
to delegate the event if you need to 'attach' the event handler before the element exists.
try
$('#second').on("click",function(){
$(this).hide();
});
To clarify why your code is not working : During the definition of the event handling of #second that div doesn't exist. You should define the event handling after you are sure that the DOM element $("#second") is present in the page.
use on()
$(document).on('click', '#second', function(){
$(this).hide();
})
refer
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.