使用JavaScript检测URL哈希值的变化

32

我正在开发一个简单的应用程序,该应用程序基于单页面(由于项目限制)并具有动态内容。我理解动态内容,但我不理解如何设置脚本,以便在URL中哈希值更改时更改

的HTML内容。

我需要一个JavaScript脚本来实现以下功能:

URL:http://foo.com/foo.html div内容:<h1>Hello World</h1>

URL:http://foo.com/foo.html#foo div内容:<h1>Foo</h1>

这应该如何工作?

请帮忙!谢谢。


请查看sammy - Brad Christie
@Bradchristie 好的,我会看一下,但是理想情况下我想尽量避免使用插件...只用jQuery可以吗? - user115422
让我们现实地看待这个问题。你要么花额外的时间编写一个库所做的事情,要么只需使用该库并继续前进。你已经在使用jQuery(一个库),因为你可能想要灵活性而不必自己编写它。此外,Sammy允许您插入占位符并对传入的哈希进行模板化(非常灵活)。 - Brad Christie
@BradChristie,了解了,我只是需要看一个例子... 我有点乱了 :( - user115422
3个回答

77

您可以监听 hashchange 事件:

$(window).on('hashchange',function(){ 
    $('h1').text(location.hash.slice(1));
});

好的,这可能听起来像一个愚蠢的问题,但是这个代码应该放在body的末尾还是head中呢?因为我总是在这方面感到困惑。 - user115422
@RPM 在头部吗?谢谢 :) - user115422
7
我认为这假设HTML5的window.onhashchange事件存在。我不相信这是jquery的本机事件,因此您需要使用插件生成触发器,或仅接受支持相当新的事件的浏览器。请注意,本文中已经包含了链接和技术术语,如果需要更详细的解释,请提供相关背景信息。 - Brad Christie
@BradChristie,你能给我展示一下使用该插件的示例吗?因为这对我没用:( - user115422

5

我个人会选择使用sammy,它可以让你灵活地模板化hashtag(添加占位符并能够读取它们)。例如:

<script src="/path/to/jquery.js"></script>
<script src="/path/to/sammy.js"></script>
<script>
  $(function(){
      // Use sammy to detect hash changes
      $.sammy(function(){
          // bind to #:page where :page can be some value
          // we're expecting and can be retrieved with this.params
          this.get('#:page',function(){
              // load some page using ajax in to an simple container
              $('#container').load('/partial/'+this.params['page']+'.html');
          });
      }).run();
  });
</script>

<a href="#foo">Load foo.html</a>
<a href="#bar">Load bar.html</a>

这里有一个例子:http://jsfiddle.net/KZknm/1/

我尝试过以下代码:<script> $(function(){ $.sammy(function(){ alert("hello"); }); }); </script>但是当我更改hashtag时,该脚本并没有弹出任何提示。 - user115422
@fermionoid:不是那样工作的。你需要用this.get(...);绑定更改。 - Brad Christie
@fermionoid:请查看我更新的答案中包含的示例。 - Brad Christie
好的,我会试一下。这里已经很晚了,所以我想我明天告诉你结果 :) 感谢你的帮助。(我已经为你的答案点赞了) - user115422

0
假设我们有一系列项目,每个项目都有一个哈希标签作为#id。
const markup = `
        <li>
            <a class="results__link" href="#${recipe.recipe_id}">
                <figure class="results__fig">
                    <img src="${recipe.image_url}" alt="${limitRecipeTitle(recipe.title)}">
                </figure>
                <div class="results__data">
                    <h4 class="results__name">${recipe.title}</h4>
                    <p class="results__author">${recipe.publisher}</p>
                </div>
            </a>
        </li>
    `;

现在当用户点击这些列表项中的任何一个或重新加载 (http://localhost:8080/#47746) 带哈希标签的项时,将触发哈希事件。为了接收到触发的哈希事件,我们必须在 app.js 中注册哈希事件监听器。

//jquery: 
['hashchange', 'load'].forEach(event => $(window).on(event, controlRecipe));
//js:
['hashchange', 'load'].forEach(event => window.addEventListener(event, controlRecipe));

在你的controlRecipe函数中捕获id

const controlRecipe = async ()=>{
//jq
  const id =  $(window)..location.hash.replace('#','');
//js
  const id = window.location.hash.replace('#','');
  if(id){
    //console.log(id);
    state.recipe = new Recipe(id);
    try {
      await state.recipe.getRecipe();
      state.recipe.calcTime();
      state.recipe.calcServings();
      console.log(state.recipe);
    } catch (error) {
      alert(error);
    }
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接