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

时间:2018-03-29 06:45:32

标签: javascript jquery html html5

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

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

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.");
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用网址(锚点)的哈希部分。 只需将您的信息添加到window.location.hash变量。

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

下面的代码将onChange事件注册到下拉列表。当下拉列表发生变化时,url的哈希值会重新写入。

当页面加载时,它会检查是否有哈希值,如果是,则选择下拉列表中的ID。

更新我编辑了我的答案并更改了代码,现在您可以更轻松地管理哈希值,并且可以管理任意数量的哈希值。 Anchorman是管理所有哈希值的小帮手。

CREATE TRIGGER update
AFTER UPDATE
   ON table_name FOR EACH ROW
BEGIN
if (`FieldName` = 'age' and `FieldValue` = 'less than 30') THEN
set NEW.point-age = 10;
 END IF;
END;
/**
 * 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');
  }
});