【发布时间】:2016-07-16 22:43:44
【问题描述】:
我要做的是检查点击事件,然后生成 html。问题是,当多次单击链接时,它会为我生成重复值。谁能看到我做错了什么?到目前为止我的代码:
(function ($) {
$.fn.hotelComparison = function () {
$('a.js-hotel-box').click(function( event ){
event.preventDefault();
var obj = $(this),
hotelId = obj.data("hotel-id");
ids = $.cookie("hotel-comparison");
if(!ids){
$.cookie("hotel-comparison", hotelId , { path: '/' });
}
else{
$.cookie("hotel-comparison", ids + "," + hotelId , { path: '/' });
}
});
favouriteHotels();
};
function favouriteHotels(){
var hotelIds = [];
$('.js-hotel-box').on('click', function(e){
e.preventDefault();
var obj = $(this);
hotelIds.push({
hotelId: $(this).data('hotel-id') ,
hotelName: $(this).data('hotel-name'),
hotelImage: $(this).data('hotel-image')
});
// check for duplicate values
var dupes = {};
var singles = [];
$.each(hotelIds, function(i, el) {
if (!dupes[el.hotelId]) {
dupes[el.hotelId] = true;
singles.push(el);
}
});
var html = '<ul class="favoriteItems">';
jQuery.each(singles, function(index, value) {
html += '<li class="hotel-image">';
html += '<a class="js-delete-hotel delete" id="'+ value.hotelId +'" href="#" title="Odebrat hotel ze schránky"><span></span></a>';
html += '<img class="hotel_image" src="'+ value.hotelImage +'" width="70px" height="70px" />';
html += '<li class="hotel-name">' + value.hotelName + '</li>';
html += '</li>';
});
html += '</ul>';
$('.hotelItems').append(html);
});
}
}(jQuery));
【问题讨论】:
标签: jquery arrays cookies plugins