-->

我如何从一个URL片段标识符(后散列值#)?(How do I get the fragment i

2019-06-17 12:56发布

例:

www.site.com/index.php#hello

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

var type = …

Answer 1:

无需jQuery的

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


Answer 2:

您可以通过下面的代码做到这一点:

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

观看演示



Answer 3:

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

在工作演示的jsfiddle



Answer 4:

使用下面的JavaScript来获取从URL后,哈希(#)的值。 你不需要使用jQuery了点。

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

我有这个代码和教程从这里- 如何使用JavaScript网址获得哈希值



Answer 5:

这很容易。 试试下面的代码

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


Answer 6:

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

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

希望这可以帮助



Answer 7:

基于AK的代码,这里是一个辅助函数。 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);


文章来源: How do I get the fragment identifier (value after hash #) from a URL?