jquery 如何从URL获取片段标识符(hash #后面的值)?

2w3kk1z5  于 2022-11-03  发布在  jQuery
关注(0)|答案(8)|浏览(186)

示例:

www.site.com/index.php#hello

使用jQuery,我想将值hello放入一个变量:

var type = …
kpbwa7wx

kpbwa7wx1#

不需要jQuery

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

由于不赞成使用String.prototype.substr,请改用substring

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

bpzcxfmw2#

您可以使用以下代码来完成此操作:

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

velaa5lx

velaa5lx3#

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

jsfiddle上运行演示

z31licg0

z31licg04#

使用下面的JavaScript从一个URL中获取hash(#)后面的值,不需要使用jQuery。

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

我从这里得到了这个代码和教程-How to get hash value from URL using JavaScript

pwuypxnk

pwuypxnk5#

这很简单。请尝试以下代码

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

neskvpey6#

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

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

我希望这能有所帮助

qlvxas9a

qlvxas9a7#

获取当前文档位置的片段

var hash = window.location.hash;

从字符串获取片段

// absolute
var url = new URL('https://example.com/path/index.html#hash');

console.log(url.hash);

// relative (second param is required, use any valid URL base)
var url2 = new URL('/path/index.html#hash2', 'http://example');

console.log(url2.hash);
kqlmhetl

kqlmhetl8#

基于A.K的代码,这里是一个帮助函数。JS Fiddle Here(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);

相关问题