使用var max 6循环,如果未单击链接,则保留空值

时间:2019-03-15 13:37:10

标签: jquery

使用以下代码,每次点击都会添加网址链接。

但是,最多需要限制6个网址。 URL最初也必须像-test.html?url1 =&url2 =&url3 =&url4 =&url5 =&url6

如果用户点击了2个项目,

test.html?url1 = google.com&url2 = yahoo.com&url3 =&url4 =&url5 =&url6

剩余的url3,url4,url5,url6-将为空值。必须将这些url 6参数作为POST脚本调用传递给后端。

谢谢

JS:

var offerListing = [];
var favouriteOfferCookie = $.cookie('favouriteOffer');
var $cookieData;
if(!favouriteOfferCookie) {
  $cookieData = $.cookie('favouriteOffer', JSON.stringify(offerListing), { path: '/', expires: 7});
}
offerListing = $.parseJSON($.cookie('favouriteOffer'));

$('.favicon-wrapper').on('click', function(){
  if($(this).find('.favicon').hasClass('selected')){
    $(this).find('.favicon').removeClass('selected');
    console.log('Remove');
    var $offerLink = $(this).closest('.offer-list-item-wrapper').attr('href');
    offerListing = offerListing.filter((ol) => ol.link != $offerLink);
  } else{
    $(this).find('.favicon').addClass('selected');
    var $offerLink = $(this).closest('.offer-list-item-wrapper').attr('href');

    //Check if link exists before adding
    var linkExists = offerListing.find((ol) => {
      return ol.link == $offerLink
    });
    if (linkExists) {
      return;
    }
    offerListing.unshift(
      { 'link': $offerLink}
    );
    $.cookie('favouriteOffer', JSON.stringify(offerListing), { path: '/', expires: 7});
    offerListing = offerListing.slice(0, 6);
    console.log('Favourite Offer', offerListing);
    // format url array to string in "url1=https://url.com" format
    const formattedUrlArr = offerListing.map((elem, i) => `url${i + 1}=${elem.link}`);
    // join to create new url
    const newUrl = `${baseUrl}?${formattedUrlArr.join('&')}`;
    console.log('newUrl: ' +newUrl);
  }
});

0 个答案:

没有答案