链接到包含用户从下拉列表中选择的页面,已选择



我的页面有许多下拉列表,我希望拥有一个功能,当用户选择某些内容时,他可以使用他选择的选项发送页面的链接。

因此,我尝试使用pushState-它更改URL,这很棒,但是当我刷新时,它实际上说该页面不存在。

function ChangeUrl(title, url) {
    if (typeof (history.pushState) != "undefined") {
        var obj = { Title: title, Url: url };
        history.pushState(obj, obj.Title, obj.Url);
    } else {
        alert("Browser does not support HTML5.");
    }
}

您可以使用URL的哈希部分(锚(。只需将您的信息添加到窗口。location.hashvarible。

以下是一个例子。但是请注意,此代码在stackoverflow上不起作用。

下面的代码在下拉列表中注册一个onchange事件。当下拉列表更改时,URL的哈希将重新定位。

当页面加载时,它检查是否有哈希

UPDATE 我编辑了更改代码的答案,现在您可以更轻松地管理Hash值,并且可以根据需要管理尽可能多的哈希。主机是管理所有哈希的小辅助对象。

/**
 * anchorman is a helper object for url hashes
 */
let anchorman = (function() {
  "use strict";
  let _hashes = {};
  /**
   * Reads the hash from the address bar of the browser
   */
  let _readHash = function() {
      if (window.location.hash) {
        let hash = window.location.hash;
        // cut of server parameter and keep only the anchors
        let pos = hash.indexOf('?');
        if (pos !== -1) {
          hash = hash.substr(0, pos);
        }
        //cut of leading dash
        if (hash.indexOf('#') === 0) {
          hash = hash.substr(1, hash.length);
        }
        //split the parameters into separate pieces
        let splitHash = hash.split("&");
        //build the parameter list array
        for (let i = 0; i < splitHash.length; i++) {
          let splitParameter = splitHash[i].split("=");
          _hashes[splitParameter[0]] = splitParameter[1];
        }
      }
    },
    /**
     * Initialise it self
     * @private
     */
    _init = function() {
      _readHash();
    },
    /**
     * Checks if a specific hash is set
     *
     * @param key
     * @returns {boolean}
     */
    hasHash = function(key) {
      _readHash();
      return _hashes.hasOwnProperty(key);
    },
    /**
     * Returns the wanted hash value
     * @param hashName string
     * @returns {*}
     */
    getHash = function(hashName) {
      if (hasHash(hashName)) {
        return _hashes[hashName];
      }
      return null;
    },
    /**
     * Returns all hash parameters as a string for the use in a address bar
     *
     * @returns {string}
     */
    toString = function() {
      let hashString = "";
      for (let key in _hashes) {
        if (_hashes.hasOwnProperty(key) && key.length > 0) {
          hashString += "&" + key + "=" + _hashes[key];
        }
      }
      return hashString;
    },
    /**
     * Updates the address bar of the browser and also the history, so back navigation is no problem
     */
    _updateAddressBar = function() {
      window.location.hash = toString();
    },
    /**
     * Updates a specific parameter in the hash, if it does not exist it will be created
     *
     * @param {string} key
     * @param {string} value
     */
    setHashValue = function(key, value) {
      _readHash();
      _hashes[key] = value;
      if (_hashes[key] === null || _hashes[key].length <= 0 || typeof(_hashes[key]) === 'undefined') {
        delete _hashes[key];
      }
      _updateAddressBar();
    },
    /**
     * Remove a specific parameter in the hash.
     *
     * @param hashKey
     */
    removeHash = function(hashKey) {
      _readHash();
      if (hasHash(hashKey)) {
        if (_hashes.hasOwnProperty(hashKey)) {
          delete _hashes[hashKey];
        }
      }
      _updateAddressBar();
    },
    /**
     * Checks if any hash is set
     * This is needed because array.length does not work because of (unknown) reasons.
     *
     * If the exceptions array is set, it will check if any hash beside these in the exception array are set.
     *
     * @param exceptions An Array with exceptions to ANY Rule
     *
     * @returns {boolean}
     */
    hasAnyHash = function(exceptions) {
      _readHash();
      for (let key in _hashes) {
        if (key.length > 0 && _hashes.hasOwnProperty(key)) {
          if (exceptions !== undefined && exceptions.indexOf(key) !== -1) {
            continue;
          }
          return true;
        }
      }
      return false;
    };
  // call the initialisation
  _init();
  // public functions
  return {
    getHash: getHash,
    hasAnyHash: hasAnyHash,
    hasHash: hasHash,
    removeHash: removeHash,
    setHashValue: setHashValue,
    toString: toString,
  };
}());
// register onChange events to the dropdowns
$('.userDropdowns').on('change', function() {
  // when a dropdown changes, write the new value to the url hash
  let dropdownId = $(this).attr('id');
  let selectedElementId = $(this).val();
  anchorman.setHashValue(dropdownId, selectedElementId);
});
// this code will run when the document is loaded
$(document).ready(function() {
  // changes the city dropdown selection if the ddCity hash value is set on page load
  let cityId = anchorman.getHash('ddCity');
  if (cityId !== null) {
    $('#ddCity').val(cityId).trigger('change');
  }
  // changes the department dropdown selection if the ddDepartment hash value is set on page load
  let departmentId = anchorman.getHash('ddDepartment');
  if (departmentId !== null) {
    $('#ddDepartment').val(departmentId).trigger('change');
  }
  // changes the section dropdown selection if the ddSection hash value is set on page load
  let sectionId = anchorman.getHash('ddSection');
  if (sectionId !== null) {
    $('#ddSection').val(sectionId).trigger('change');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddCity" class="userDropdowns">
    <option value="1">NY</option>
    <option value="2">Paris</option>
    <option value="3">Berlin</option>
    <option value="4">London</option>
</select>
<select id="ddDepartment" class="userDropdowns">
    <option value="1">North</option>
    <option value="2">South</option>
    <option value="3">East</option>
    <option value="4">West</option>
</select>
<select id="ddSection" class="userDropdowns">
    <option value="1">Section 1</option>
    <option value="2">Section 2</option>
    <option value="3">Section 3</option>
    <option value="4">Section 4</option>
</select>

最新更新