jQuery:检查hash是否包含

use*_*796 0 html javascript hash jquery

我想在继续之前尝试检查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);
});
Run Code Online (Sandbox Code Playgroud)

因此,如果哈希是www.website.com/#news-item-03它将用户水平滑动到第3个新闻故事,这非常有用!我只希望这个函数触发,但是如果哈希news-item显然包含每个都会改变后的数字,但是如果哈希开始于news-item那时我想要触发上面的函数,我甚至不确定它是否可能,任何建议将不胜感激!

Nia*_*son 6

不需要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
     }
 }
Run Code Online (Sandbox Code Playgroud)

  • 它将是`window.location.hash.indexOf('news-item')== 1`,#将在索引0上 (2认同)