javascript jQuery:检查哈希是否包含
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19889005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: Check if hash contains
提问by user1374796
I'm looking to try and check if the hash in the url contains a certain value before proceeding, I have a function that works like so:
在继续之前,我想尝试检查 url 中的哈希值是否包含某个值,我有一个像这样工作的函数:
$(window).load(function () {
var hash = window.location.hash,
number = $(hash).index(),
width = 403,
final = width * number;
setTimeout(function () {
$('.news-inner-wrap').animate({
'marginLeft': "-=" + final + "px"
});
}, 1000);
});
So if the hash is www.website.com/#news-item-03
it will slide the user horizontally along to the 3rd news story, this works great!. I only want this function to fire though if the hash contains news-item
obviously the number after each will change, but if the hash begins with news-item
then I want the function above to be fired, I'm not even sure it this is at all possible, any suggestions would be greatly appreciated!
因此,如果散列是,www.website.com/#news-item-03
它会将用户水平滑动到第三个新闻故事,这很好用!。我只希望这个函数被触发,尽管如果散列news-item
明显包含每个之后的数字会改变,但是如果散列开始,news-item
那么我希望上面的函数被触发,我什至不确定这是否可能建议将不胜感激!
回答by Niall Paterson
No need for jQuery, this should work nicely
不需要 jQuery,这应该很好用
if (window.location.hash) {
if (window.location.hash.indexOf('news-item') == 1) { // not 0 because # is first character of window.location.hash
// it's at the start
}
else if (window.location.hash.indexOf('news-item') != -1) {
// it's there, but not at the start
}
else {
// not there
}
}
回答by Peter van der Wal
Use a regular expression:
使用正则表达式:
var matches = hash.match(/^#news-item-([0-9]+)$/);
if (matches) {
var number = matches[1];
// Rest of your code
}