假设jquery .each
循环:
function reverifyDiscounts() {
//everything we need to verify a discount is already on the page.
//we'll remove the "bad" discounts when we submit the page
console.info("Entering reverification");
//event discounts are always valid once they're on the page because it's for the event
$(".discountPromoItem").each(function () {
//skip events
if ($(this).attr("appliesto") == $("#hdnEventID").val()) {
return true;
}
//we just need to make sure that the checkbox that the appliesto attribute references is checked!
if (!$("checkbox[attribute$='" + $(this).attr("applitesto") + "']").is(":checked")) {
//we also need to remove the promo code from the list of promo codes entered into the hidden textboxes
$("#hdnAppliedPromoCode").val($("#hdnAppliedPromoCode").val().replace($(this).attr("code"), ""));
//the item that it applies to is no longer selected and the promo must be removed
$(this).remove(); //can't remove $(this) while inside the loop for whatever reason.
}
});
recalculate();
}
为什么$(this).remove()
失败或我做错了什么?
答案 0 :(得分:6)
更新
除了最后丢失的)
之外,您的代码确实有效:http://jsfiddle.net/TrueBlueAussie/hdc9ke9k/
问题必须在if
测试中。
尝试使用过滤器然后执行最后删除:
function reverifyDiscounts() {
//everything we need to verify a discount is already on the page.
//we'll remove the "bad" discounts when we submit the page
console.info("Entering reverification");
//event discounts are always valid once they're on the page because it's for the event
$(".discountPromoItem").filter(function () {
//skip events
if ($(this).attr("appliesto") == $("#hdnEventID").val()) {
return false;
}
//we just need to make sure that the checkbox that the appliesto attribute references is checked!
if (!$("checkbox[attribute$='" + $(this).attr("applitesto") + "']").is(":checked")) {
$("#hdnAppliedPromoCode").val($("#hdnAppliedPromoCode").val().replace($(this).attr("code"), ""));
return true;
}
}).remove();
recalculate();
}
问题原始版本的原始代码
带有ID选择器的each
没有任何意义,因为ID 必须是唯一的,并且只有第一个匹配。
原因是浏览器维护每个ID与单个DOM元素的高速查找字典。 jQuery(和JavaScript)只能通过ID获得第一个匹配。
使用类代替多项匹配:
$(".thatThing").each(function(){
if (someBoolCondition){
$(this).remove();
}
});