简体   繁体   中英

How can I traverse through cookie and then upon clicking a button change the url depending on values from cookie

I have a cookie dataid giving data as below "D_2781467,D_2792290,D_2803725,D_2677313,D_2799569,D_2805134,D_2758142,D_2802506,D_2802509,D_2802508,D_2803726,D_2652515"

And in the body we have valies as below

<body class="mycars" data-listing-id="2792290">

And the URL will be like

http://www.abcd.com/c_f_s/D_2792290/xyz.html

What I want is that in this page upon clicking a button , the user is taken to next url as in

http://www.abcd.com/c_f_s/D_2803725

So basically somehow we need to traverse through the cookie and get the index and on pressing the button change the url with the number received from the cookie

You can do it like,

HTML

<a href="javascript:;" id="next">Next</a>

SCRIPT

$(function(){
    var dataArr = ['D_2781467', 'D_2792290', 'D_2803725', 'D_2677313', 'D_2799569',
                   'D_2805134', 'D_2758142', 'D_2802506', 'D_2802509','D_2802508',
                   'D_2803726', 'D_2652515'];
    var index = 0;
    $.cookie('index', 0);

    $('#next').on('click', function (e) {  
        e.preventDefault();
        if (index < dataArr.length-1) { // check index length
            index++ ;// increment index
        } else {
            index = 0; // reset index             
        }
        var currentIndex = $.cookie('index'); // get current cookie index from cookie
        $.cookie('index', index);        
        alert('http://www.abcd.com/c_f_s/' + dataArr[currentIndex]);
    });
});

You can use cookie plugin

Live Demo

Here is how I would do it (not tested, but this is the basic idea).

using the getCookie function from: http://www.w3schools.com/js/js_cookies.asp

$('#button').click(function() {
 var cook = getCookie('dataid').split(',')
 var myId = $('body').eq(0).attr('data-listing-id')
 var index = cook.indexOf('D_'+myId)
 if (index == -1 || index == cook.length - 1)
  return;
 document.location = 'http://www.abcd.com/c_f_s/D_'+cook[index+1]
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM