2011-06-14 183 views
2

我已經動態地在頁面中使用jquery添加以下功能的元素。選擇動態添加元素與jQuery ...

function addtocart(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); 
        } 
       }); 
      } 
     ); 
} 

但我不能在這個新元素上調用任何事件。

jQuery('.test').hover(function(){ 
      alert('asdf'); 
     }); 

任何建議

回答

2

,當你這樣做

jQuery('.test').hover(function(){ 
      alert('asdf'); 
     }); 

你正在做的只是一次設定的事件處理程序(瀏覽器設置功能的事件處理程序爲所有以「test」的對象如果要爲每個「測試」元素設置處理程序,則應該使用intead

jQuery('.test').live('hover', function(){ 
      alert('asdf'); 
     }); 
2

必須使用live()功能附加事件添加到頁面加載後的DOM元素。

嘗試

jQuery('.test').live('hover', function(){ 
      alert('asdf'); 
     }); 

這是因爲事件被附加到元素通常在DOM它已經準備好,如果你添加的元素之後,他們有不附帶任何事件。 Live()使用事件冒泡來解決這個問題。

0

於事件動態創建的元件上結合,jQuery提供休耕兩個函數來acomplish這 -

  1. delegate
  2. live

可以在同樣的方式使用作爲delegate我已經使用live

jQuery('.test').live('hover', function(){    
       alert('asdf');   
    }); 

委託生活的優勢在於,您可以在委託中進行鏈接,但不能懸停。

2

嘗試

jQuery(".test").live({ 
    mouseenter: 
     function() 
     { 

     }, 
    mouseleave: 
     function() 
     { 

     } 
    });