Reputation: 1077
I can't get an event to trigger when you click on an element, and this element is only displayed when you hover of a td element.
//Hovering over a td element displayed a Span
$('td').hover(
function() {$(this).append('<span class="editCell">hello</span>')},
function() {$(this).find('span:last').remove()}
)
//Clicking on that span, it's supposed to trigger alert. But it doesn't.
$('.editCell').click( function(){
alert('hello');
})
Upvotes: 1
Views: 156
Reputation: 7759
Because .click()
event doesn't work on dynamically added content.
Use .on() instead
$("td").on("click", ".editCell" ,function(){
});
td
and bind click
event only to that selector.The above is called delegated-events
.
You also can do it like this :
$(".editCell").on("click",function(){
});
Upvotes: 2
Reputation: 337560
This is because the editCell
element is being appended after page load. You need to delegate the event to the nearest static element. Try this:
$("td").on("click", ".editCell", function() {
alert("hello");
});
The td
selector is still a little broad though, you should put an id on the closest parent of editCell
for the sake of performance.
Upvotes: 0