I have dynamically added an element in page using jquery with following function.
function addtocar开发者_C百科t(popid)
{
jQuery('#thumb'+popid+' button').attr("disabled", true);
//jQuery('#thumb'+popid+' button').html("Added");
position = jQuery('#cart').offset();
source = jQuery('#thumb'+popid+' img').offset();
jQuery('#thumb'+popid+' img').clone().css({'display':'block', 'position':'absolute','top':source.top,'left':source.left}).appendTo('body').addClass('animation');
jQuery('.animation').animate(
{'left': position.left, 'top':position.top},
'slow',
function(){
jQuery(this).remove();
jQuery('#cart').append('<li class="test">'+jQuery('#thumb'+popid+' .title').html()+'<a href="#">X</a></li>');
jQuery.ajax({
url: "creatives.php?ajax=1&creativeid="+popid,
success:function(data){
jQuery('.itemstodwnload span').html(data);
}
});
}
);
}
but i cannot call any event on this new element.
jQuery('.test').hover(function(){
alert('asdf');
});
any suggestion
when you set the event handler by doing
jQuery('.test').hover(function(){
alert('asdf');
});
you're doing just once (the browser set that function as event handler for all the object with "test" class present at the time of executing this line. To have an handler setted for every "test" element, you should use intead
jQuery('.test').live('hover', function(){
alert('asdf');
});
You must use the live() function to attach events to elements added to the DOM after page loading.
try
jQuery('.test').live('hover', function(){
alert('asdf');
});
This is because events are attached to elements usually when DOM it's ready and if you add elements afterwards they have no events attached. Live() uses event bubbling to work around this.
Try
jQuery(".test").live({
mouseenter:
function()
{
},
mouseleave:
function()
{
}
});
to bind an event on dynamically created element, jquery provides fallowing two functions to acomplish this-
- delegate
- live
you can use delegate
in same way as i have used live
jQuery('.test').live('hover', function(){
alert('asdf');
});
Advantage of delegate over live is that you can do chaining in delegate but not in hover.
精彩评论