Detect change in hash value of URL using JavaScript

前端 未结 3 1204
清酒与你
清酒与你 2021-01-30 14:05

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

相关标签:
3条回答
  • 2021-01-30 14:13

    You can listen to the hashchange event:

    $(window).on('hashchange',function(){ 
        $('h1').text(location.hash.slice(1));
    });
    
    0 讨论(0)
  • 2021-01-30 14:15

    personally, I'd use sammy which gives you the flexibility to template the hashtag (add placeholders and be able to read them back). 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>
    

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

    0 讨论(0)
  • 2021-01-30 14:24

    Suppose we have list of items, each items has a hash tag as #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

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

    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);
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题