开发者

Applying JQuery effects to newly added elements [duplicate]

开发者 https://www.devze.com 2023-03-15 15:00 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Jquery live() vs delegate()
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消