cookie to remember dropdown selection

2019-08-04 13:32发布

问题:

I have a simple dropdown and user selects a choice and the page refreshes with the selection added to the URL as a querystring. But i want to also keep the selected state of dropdown after the refresh. How do i do that using jquery or cookie?

<select id="MyDropDown" onchange="window.open(this.options[this.selectedIndex].value,'_top')">

  <option value="http://mysite.com/default1.aspx?alpha=A">A</option>
  <option value="http://mysite.com/default1.aspx?alpha=B">B</option>
  <option value="http://mysite.com/default1.aspx?alpha=C">C</option>
</select>

回答1:

You can use the jquery cookie plugin and write code as shown below

$('#MyDropDown').change(function() {
    $.cookie('mycookie', $(this).val(), {
             expires: 365}
             );
}


回答2:

A better way to save the state without putting data on each html request is to use HTML5 Local storage. Here is a good example how to use it: http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-learning-about-html5-local-storage/



回答3:

Does setting a cookie not work?

<select id="MyDropDown" onchange="document.cookie=this.selectedIndex; window.open(this.options[this.selectedIndex].value,'_top')">

You could also just extract the value of "alpha" passed with the URL.