2013-07-21 12 views
0

嘿,我已經嘗試做一個自定義的腳本來顯示購物車。而我認爲我最近的完成,但我有一個問題,它只能調用一次函數。我的jQuery函數只能使用一次

http://articles-authors.com/order-form/你可以看到車的右頂部,當網站加載功能已經負載創建購物車。但是,當嘗試過車nothning懸停發生,應該有它調用另一個函數來重新創建購物車和活動類設置類的HTML元素#cart。

下面是代碼:

首先要調用的函數的車創造功能

makeCartWithoutActive(); 
$("#cart").mouseenter(function(){ 
makeCartWithActive(); 
}).mouseleave(function(){ 
makeCartWithoutActive(); 

});

的原因是使用了mouseenter是因爲使用jQuery 2.0.3和生活已經刪除1.7,我認爲。

在這裏你可以看到功能應該重新創建購物車,然後設置類主動到#cart這樣的車會一直顯示

function makeCartWithActive(){ 
$.get("http://articles-authors.com/order-form/cart/get",function(data) { 
    var html = ""; 
    if(data.msg === false){ 
     html = '<div id="cart" class="right active">'+ 
      '<div class="heading"><a><span id="cart-total">0 item(s) - $0.00</span></a></div>'+ 
      '<div class="content"><div class="empty">'+data.respone+'</div></div></div>'; 
    $("#cart").replaceWith(html); 

    }else{ 

    html = '<div id="cart" class="right active"><div class="heading"><a><span id="cart-total">'+data.totalitem+' item(s) - $'+data.totalprice+'</span></a></div>'+ 
      '<div class="content"><div class="mini-cart-info"><table><tbody>'; 

    $.each(data.data, function(i, currProgram) { 
     $.each(currProgram, function(key,val) { 
      html += '<tr><td class="name">'+val.name+'</td><td class="quantity">x '+val.quantity+ 
        '</td><td class="total">$'+val.price+'</td><td class="remove"><img src="http://articles-authors.com/order-form/img/remove-small.png'+ 
        '" onclick="RemoveItem('+val.rowid+');" width="12" height="12" title="Remove" alt="Remove"></td></tr>'; 
     }); 
    }); 

     html += '</tbody></table></div>'+ 
      '<div class="mini-cart-total"><table><tbody><tr><td align="right"><b>Sub-Total:</b></td><td align="right">'+data.totalprice+'</td></tr><tr><td align="right"><b>Total:</b></td><td align="right">'+data.totalprice+'</td></tr></tbody></table></div>'+ 
      '<div class="checkout"><a class="button" href="http://articles-authors.com/order-form/cart">Checkout</a></div></div></div>'; 


    $("#cart").replaceWith(html); 
}}, 

"jsonp"); 

} 

希望有人能幫助我。我還在新的jQuery/JavaScript的所以不知道爲什麼發生這種情況

在此先感謝

+2

您要更換'#購物車「,當然它只能工作一次,你附加事件處理程序的元素消失了嗎? – adeneo

+0

現場已經depriciated但你可以「上」其現場更換使用 –

回答

0
$(document).on('mouseenter', '#cart', function(){ 
    makeCartWithActive 
}).on('mouseleave', '#cart', function(){ 
    makeCartWithoutActive 
}); 

你要替換的元素,因此處理器消失。您需要將該函數委託給最近的靜態父元素。

我選擇文件,但對於性能,您應該選擇一些接近#cart

2

使用委託的事件處理程序

$(document).on('mouseenter', '#cart', function(){ 
    makeCartWithActive(); 
}); 

$(document).on('mouseleave', '#cart', function(){ 
    makeCartWithoutActive(); 
}); 

或者你可以使用

$(document).on({ 
    "mouseenter" : function(e) { makeCartWithActive(); }, 
    "mouseleave" : function(e) { makeCartWithoutActive(); } 
}, "#cart");