我正在使用 javascript 创建一个简单的购物车,如果没有用于移除商品的按钮,购物车会是什么?
购物车是使用 javascript 即时创建的,因此元素不会在页面加载时存在。但是,这应该不是问题吧?
$(".removeFromCart").on("click",function(e){
alert("GO AWAY PLEASE..");
var tuoteID = $(this).attr("data-id");
deleteFromCart(tuoteID);
});
元素(动态创建)看起来像这样:
<a href="#" class="removeFromCart" data-id="2">×</a>
但是不会触发。例如,如果我用 p
替换 .replaceFromCart
,它会在我每次点击一个段落时触发。
这不是我第一次遇到 .on()
的问题,它总是需要我一半的头发才能解决,所以也许有更多经验的人可以指出我的问题我做错了。
您需要事件委托(delegate),使用其他版本的 jQuery on()功能。您必须在执行绑定(bind)代码时提供存在的静态父级,或者您可以委托(delegate)给 body
或 document
。
$(document).on("click",".removeFromCart", function(e){
alert("GO AWAY PLEASE..");
var tuoteID = $(this).attr("data-id");
deleteFromCart(tuoteID);
});
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers, jQuery doc.