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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14970708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:31:02  来源:igfitidea点击:

Detect change in hash value of URL using JavaScript

javascriptjquery

提问by user115422

I'm working on a simple application which is single page based (due to project restrictions) and has dynamic content. I understand the dynamic content alright but what I don't understand is how to set-up a script that changes the html of a divwhen the hash value in the URL changes.

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

I need a JavaScript script to work as such:

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

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

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

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

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

How would this work?

这将如何运作?

Please help! Thanks.

请帮忙!谢谢。

回答by undefined

You can listen to the hashchangeevent:

您可以收听hashchange事件:

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

回答by Brad Christie

personally, I'd use sammywhich gives you the flexibility to template the hashtag (add placeholders and be able to read them back). e.g.

就个人而言,我会使用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>

An example can be found here: http://jsfiddle.net/KZknm/1/

一个例子可以在这里找到:http: //jsfiddle.net/KZknm/1/

回答by Lord

Suppose we have list of items, each items has a hash tag as #id

假设我们有项目列表,每个项目都有一个 #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>
    `;

Now when a user click on any of those list item or reload (http://localhost:8080/#47746) an item with hash tag, hash event will be fired. To recive the fired hash event we must register hash event listener in our app.js

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

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

catch the id in your controlRecipe function

在 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);
    }
  }
}