Javascript jQuery以url哈希为条件
在jQuery中,如何检查用户是否正在访问特定的直接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
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