功能描述:

根据客户选择下拉框,同步中部分超链的请求传递参数与下拉框中的值相等。

代码中用到JQuery的cookie插件:

jquery.cookie.js
jquery.cookie.pack.js

关于该插件不做过多介绍,可以通过google获得更多信息。

页面部分:

假设页面有一个用于标识状态的select

<select >彩信</option>
    ......
</select>

并且有一些需要同步的链接,为了方便JQuery查找遍历这些链接,所以为他们统一命名为nav。

同时将访问链接的个性化部分记录在class中方便JQuery读取生成新的url。如下:

<a name="nav" href="#" class="action1.do">urlName1</a>
<a name="nav" href="#" class="action2.do">urlName2</a>
......
<a name="nav" href="#" class="action9.do">urlName9</a>

JS脚本部分:

在客户第一次使用没有cookie记录时,设置默认值:

if($.cookie('_type)== null) $.cookie('_type, 'sms');

遍历修改URL的函数,同时为了可以在其他地方操作该函数,需要为创建一个句柄:

var updateUrl = function(){
    $("a[name='nav']").each(function(){                   //遍历所有name为nav的连接
        this.href = '/' + $(this).attr("class") + '.do?type=' + $.cookie('_type');
   });
}

将cookie的值与select的默认选择项同步:

$("#type").val($.cookie('_ype'));

JQuery的一个好处就是在调用它的一些函数后仍然返回当前的对象,因此我们可以继续添加onChange事件:

$("#type").val($.cookie('_type')).change(function(){
    $.cookie('_type', $(this).val());                            //将选择的值存入cookie中
    updateUrl ();                                                       //更新url
});

最后完整的代码如下:

$(document).ready(function(){
    if($.cookie('_type')== null) $.cookie('_type', 'sms');
    updateUrl();
    $("#type").val($.cookie('_type')).change(function(){
        $.cookie('_type', $(this).val());
        updateUrl();
    });
});
var updateUrl= function(){
    $("a[name='nav']").each(function(){
        this.href = '/' + $(this).attr("class") + '.do?type'=' + $.cookie('_type');
    });
}

 

相关文章:

  • 2022-12-23
  • 2021-08-09
  • 2021-11-07
  • 2021-10-07
  • 2022-12-23
  • 2022-12-23
  • 2021-11-22
  • 2022-12-23
猜你喜欢
  • 2021-04-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-16
  • 2022-12-23
相关资源
相似解决方案