Applying JQuery effects to newly added elements [duplicate]
Possible Duplicate:
Jquery live() vs delegate()
I am having some problems applying JQuery to functions that I a开发者_C百科dd to the DOM after the page is loaded. I am using the following code to add new rows to a table body:
$("tbody").load("php/create_rows.php?" + $.param({ "type": "unique", "unit": "day", "interval": 2 }));
It works well. The rows get added, but Jquery functions that work on the rows in the table body do not affect the new rows. For example, mouseovers on rows are supposed to have a class applied to them that changes the background color:
$('tbody tr').hover(function() {
$(this).find('td').addClass('hover');
}, function() {
$(this).find('td').removeClass('hover');
});
It is not working, though. It works for code that already appears on the page, code that is not generated from Jquery.
You must wrap your
$('tbody tr').hover(function() {
into a function and when you add a dynamic element to the DOM you need to call the function like this
function something (){
$('tbody tr').hover(function() {
$(this).find('td').addClass('hover');
}, function() {
$(this).find('td').removeClass('hover');
});
}
$("document").append(someelement);
something();
example done with a input field http://jsfiddle.net/MKcaH/1/
and come to think about it you could use [1]: http://api.jquery.com/delegate/ "delegate"
try replacing your code:
$('tbody tr').hover(function() {
with
$('tbody tr').live('hover', function(){
That should make the new stuff work.
精彩评论