简体   繁体   中英

jQuery: attach an event immediately after setting up the HTML content

first this is an exemple of my jQuery code that I use in a function to do pagination:

// new_content is a variable that holds the html I want to add to a div
$('div#my_div').html(new_content);
$("div#my_div a.details").hover(function(){         
    $(this).fadeIn(); //code to execute when the mouse get in
}, function(){
    $(this).fadeOut(); //code to execute when the mouse get out
});  

BUT the hover event does not work at all, and I belive that this is caused because the DOM is not ready yet!

and to get around this I used set up a timer like this:

$('div#my_div').html(new_content);

window.setTimeout(
  $("div#my_div a.details").hover(function(){           
    $(this).fadeIn(); //code to execute when the mouse get in
  }, function(){
    $(this).fadeOut(); //code to execute when the mouse get out
  });
,100); 

I asked this question because I'm sure that this is not the right way to attach an event immediatly after the html method (maybe it didn't it's work.).

si I hope someone show me the right way to do it.

You would want to use the live mouseover mouseleave events

$("div#my_div").live({
       mouseenter: function()
       {

       },
       mouseleave: function()
       {

       }
    }
);

Alternately you could do:

$('div#my_div').live('mouseover mouseout', function(event) {
    if (event.type == 'mouseover') {
        // do something on mouseover
    } else {
        // do something on mouseout
    }
});

UPDATE

In newer versions of jQuery you can do it like this

$('body').on('mouseover','#my_div', function(){});
$('body').on('mouseout', '#my_div', function(){});

Maybe you need to use the live() method. As you can read here , it seems that you will need to separate the two events:

.live("mouseenter", function() {...})
.live("mouseleave", function() {...});

UPDATE: Someone voted me up, so if someone gets here, I recommend to read the on() documentation ( here ) as live was deprecated long ago. Also, it may be interesting to see mouseenter() ( link ) and mouseleave() ( link ). The idea is the same as with live .

you can check out.live function of jquery. Here is the link http://api.jquery.com/live/

It is better to use a delegate rather than live, as live is essentially a delegate on the document.body causing it to have to bubble much longer.

Here is an example using a delegate: http://jsfiddle.net/Akkuma/wLDpT/

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