简体   繁体   English

如何遍历Cookie,然后单击按钮,根据Cookie中的值更改网址

[英]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" 我有一个Cookie数据ID,其数据如下所示:“ 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 URL将像

http://www.abcd.com/c_f_s/D_2792290/xyz.html 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 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 因此,基本上,我们需要以某种方式遍历cookie并获取索引,然后按一下按钮,以从cookie接收到的数字更改网址

You can do it like, 你可以这样

HTML 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 您可以使用Cookie插件

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 使用http://www.w3schools.com/js/js_cookies.asp中的getCookie函数

$('#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]
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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