【问题标题】:jQuery: Check if hash containsjQuery:检查哈希是否包含
【发布时间】:2013-11-22 05:32:13
【问题描述】:

我希望在继续之前尝试检查 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);
});

因此,如果哈希是www.website.com/#news-item-03,它将使用户水平滑动到第三条新闻故事,这很好用!我只希望这个函数触发,虽然如果哈希包含news-item,显然每个后面的数字都会改变,但是如果哈希以news-item开头,那么我希望上面的函数被触发,我什至不确定这个完全有可能,任何建议将不胜感激!

【问题讨论】:

    标签: javascript jquery html hash


    【解决方案1】:

    不需要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
         }
     }
    

    【讨论】:

    • 它将是window.location.hash.indexOf('news-item') == 1,# 将在索引 0 上
    【解决方案2】:

    使用正则表达式:

    var matches = hash.match(/^#news-item-([0-9]+)$/);
    if (matches) {
        var number = matches[1];
        // Rest of your code
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-28
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2014-04-06
      • 2019-08-08
      • 2018-02-18
      • 1970-01-01
      • 2015-03-28
      相关资源
      最近更新 更多