Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery以url哈希为条件_Javascript_Jquery - Fatal编程技术网

Javascript jQuery以url哈希为条件

Javascript jQuery以url哈希为条件,javascript,jquery,Javascript,Jquery,在jQuery中,如何检查用户是否正在访问特定的直接id链接url 例如: 在这种情况下,我喜欢检查foo 我喜欢这样的东西: if(jQuery.urlHasHash("foo")) { //logic here } 不需要jQuery,您的浏览器通过document.location.hash 如果要检查页面上是否存在此类ID: var hash = document.location.hash.replace(/^#/, ''); if (document.location

在jQuery中,如何检查用户是否正在访问特定的直接
id
链接url

例如:

在这种情况下,我喜欢检查
foo

我喜欢这样的东西:

if(jQuery.urlHasHash("foo")) {
    //logic here
 }

不需要jQuery,您的浏览器通过
document.location.hash

如果要检查页面上是否存在此类ID:

var hash = document.location.hash.replace(/^#/, '');

if (document.location.hash != '' && document.getElementById(hash) { 
  // or just: $(document.location.hash)
  // ...
}

试试这个演示

这可能适合您的需要
:)

代码

$(function(){
    //var href = location.href; // get the url
    var href = "http://mydomain.com/#foo"; // example url
    var split = href.split("#"); // split the string; usually there'll be only one # in an url so there'll be only two parts after the splitting
    var afterSplit = "Error parsing url";
    if(split[1] != null){
        afterSplit = split[1];
    }
    // If everything went well shows split[1], if not then de default error message is shown
    alert(afterSplit);
});
试试我的JSFIDLE:

或者只是

var url = "http://mydomain.com/#foo";
var page = url.substring(url.lastIndexOf('/') + 1); // #foo
之后,您可以使用if语句了解
if(page==“foo”)

var url = "http://mydomain.com/#foo";
var page = url.substring(url.lastIndexOf('/') + 1); // #foo