例子:

www.site.com/index.php#hello

使用jQuery,我想把值hello放在一个变量中:

var type = …

当前回答

我有运行时的URL,下面给出了正确的答案:

let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);

希望这能有所帮助

其他回答

不需要jQuery

var type = window.location.hash.substr(1);

由于String.prototype.substr已弃用,请使用substring代替。

var type = window.location.hash.substring(1);

你可以使用以下代码:

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);

看到演示

var url ='www.site.com/index.php#hello';
var type = url.split('#');
var hash = '';
if(type.length > 1)
  hash = type[1];
alert(hash);

jsfiddle的工作演示

基于A.K的代码,这里有一个Helper函数。JS提琴这里(http://jsfiddle.net/M5vsL/1/)…

// Helper Method Defined Here.
(function (helper, $) {
    // This is now a utility function to "Get the Document Hash"
    helper.getDocumentHash = function (urlString) {
        var hashValue = "";

        if (urlString.indexOf('#') != -1) {
            hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
        }
        return hashValue;
    };
})(this.helper = this.helper || {}, jQuery);

这很简单。试试下面的代码

$(document).ready(function(){
  var hashValue = location.hash.replace(/^#/, '');  
  //do something with the value here  
});