使用JavaScript检测URL哈希值的更改

Detect change in hash value of URL using JavaScript

本文关键字:哈希值 URL JavaScript 检测 使用      更新时间:2023-09-26

我正在开发一个简单的应用程序,该应用程序基于单页(由于项目限制)并具有动态内容。我很理解动态内容,但我不明白的是,当URL中的哈希值发生变化时,如何设置一个脚本来更改div的html。

我需要一个JavaScript脚本来这样工作:

Url:http://foo.com/foo.htmldiv内容:<h1>Hello World</h1>

Url:http://foo.com/foo.html#foodiv内容:<h1>Foo</h1>

这是怎么回事?

请帮忙!谢谢

您可以监听hashchange事件:

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

就我个人而言,我会使用sammy,它为您提供了模板化标签的灵活性(添加占位符并能够读回它们)。例如

<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/

假设我们有一个项目列表,每个项目都有一个散列标签#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)具有hash标记的项,将触发hash事件。要接收触发的哈希事件,我们必须在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);
    }
  }
}