我尝试制作自定义脚本来显示购物车。我想我快完成了,但我遇到了一个问题,我只能调用该函数一次。
关于 http://articles-authors.com/order-form/您可以在右上角看到购物车,当网站加载时,已加载创建购物车的功能。但是当尝试将鼠标悬停在购物车上时,什么也没有发生,它应该调用另一个函数来重新创建购物车并将该类设置为 html 元素 #cart
的事件类。
代码如下:
首先是调用购物车创建函数的函数
makeCartWithoutActive();
$("#cart").mouseenter(function(){
makeCartWithActive();
}).mouseleave(function(){
makeCartWithoutActive();
});
使用 mouseenter
的原因是因为我使用 jQuery 2.0.3,我认为 live 在 1.7 中已被删除。
在这里您可以看到应该重新创建购物车的函数,然后将类 active 设置为 #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 的新手,所以不知道为什么会这样。
最佳答案
使用委托(delegate)的事件处理程序
$(document).on('mouseenter', '#cart', function(){
makeCartWithActive();
});
$(document).on('mouseleave', '#cart', function(){
makeCartWithoutActive();
});
或者你可以使用
$(document).on({
"mouseenter" : function(e) { makeCartWithActive(); },
"mouseleave" : function(e) { makeCartWithoutActive(); }
}, "#cart");
关于javascript - 我的jQuery函数只能第一次运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772737/