选择元素设置网址参数以记住选项

时间:2019-10-17 15:30:25

标签: javascript url select parameters dropdown

使用以下命令,我可以在url中设置参数:

function setParam(name, value) {
    var l = window.location;

    /* build params */
    var params = {};
    var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;
    var s = l.search;
    for (var r = x.exec(s); r; r = x.exec(s)) {
      r[1] = decodeURIComponent(r[1]);
      if (!r[2]) r[2] = '%%';
      params[r[1]] = r[2];
    }

    /** Check to see if the param exist already
    Delete if it exist, set it, if it doesn't
    **/
    if (params[name] && value == params[name]) {
      delete params[name];
    } else if (params[name] && value != params[name]) {
      delete params[name];
      params[name] = encodeURIComponent(value);
    } else {
      params[name] = encodeURIComponent(value);
    }

    /* set param */

    /* build search */
    var search = [];
    for (var i in params) {
      var p = encodeURIComponent(i);
      var v = params[i];
      if (v != '%%') p += '=' + v;
      search.push(p);
    }
    search = search.join('&');

        /* execute search */``
    l.search = search;
  }

这取自How to remove a parameter from a url?,但我使用选择下拉列表代替了链接:

<select onchange="location = this.value;">
<option value="">Choose a category</option>
<option value="javascript:setParam('tex_magic_powers', 'high')">Magic Powers: High</option>
<option value="javascript:setParam('tex_magic_powers', 'low');">Magic Powers: Low</option>
</select> 

可以正常更新url,但是选择表单会弹回到“选择类别”。如何记住用户选择的下拉菜单?

0 个答案:

没有答案