繁体   English   中英

使选择选项保持选中状态。 饼干?

[英]Making a select option stay selected. Cookies?

我有一个非常简单的选择选项,希望它在单击时触发刷新和特定操作。 但是在开始之前,我想知道在进行任何刷新或操作后如何保持选中状态。

<select name="countries" id="countries" style="width:180px;">
<option value='us'>United States</option>
<option value='gb'>United Kingdom</option>
</select>

任何想法,我都研究过cookie,但希望对此有所帮助。

您必须包含jquery.cookies.js

http://code.google.com/p/cookies/wiki/文档

    <script type="text/javascript">
    function change_action(selected_value)
    {
       $.removeCookie("test");
       $.cookie("test", selected_value);
       //make select box selected by placing a id

       //Even this line is not necessary now
       //$('#'+selected_value).attr('selected', true);

       //Provide the URL needs to be redirected
       window.location.href = '';
    }
    </script>

以下是html代码,

//In php check whether cookie is working
   <?php
   echo $_cookie('test');
   ?>
    <select name="countries" id="countries" style="width:180px;" onchange="return change_action(this.value);">
        <option value='us' id="us" <?php if($_cookie('test') == 'us') { ?> ?>selected='selected'<?php } ?>>United States</option>
        <option value='gb' id="gb" <?php if($_cookie('test') == 'gb') { ?> ?>selected='selected'<?php } ?>>United Kingdom</option>
        </select>

选中此项,在Jquery中完成,有一些您可能不需要的代码,这是针对您为您的选项修改的其他问题而完成的

  $(document).ready(function(e){
     var name = "Country=";
     var ca = document.cookie.split(';');
     for(var i=0; i<ca.length; i++)
  {
  var c = ca[i].trim();
  if (c.indexOf(name)==0) $('#countries').val(c.substring(name.length,c.length));
  }
});

$('#countries').change(function(e)
{
    var cookieVal = "Country="+$(this).val();
document.cookie = cookieVal ;

});

http://jsfiddle.net/AmarnathRShenoy/HM3Zj/2/

<select name="countries" id="countries" style="width:180px;" onchange="change_language(this.value)">
<option value='us' id='us'>United States</option>
<option value='gb' id='gb'>United Kingdom</option>
</select>

<script>
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}




function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) 
  {
  var c = ca[i].trim();
  if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
return "";
}


function change_language(lang)
{
setCookie("flag_option_dropdown",current_flag,30);
var flag_current_option_dropdown=getCookie("flag_option_dropdown");
document.getElementById(flag_current_option_dropdown).setAttribute("selected","selected");
}

change_language("gb"); //by default




<script>

您可以使用语言翻译,我已经用这种方式解决了这个问题。 祝你好运

暂无
暂无

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

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