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

时间:2013-02-20 01:22:13

标签: javascript jquery

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

我需要一个JavaScript脚本才能正常工作:

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

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

这将如何运作?

请帮忙!感谢。

3 个答案:

答案 0 :(得分:71)

您可以收听hashchange事件:

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

答案 1 :(得分:5)

就个人而言,我使用sammy,这使您可以灵活地对主题标签进行模板化(添加占位符并能够将其读回)。 e.g。

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

答案 2 :(得分: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);
    }
  }
}