Detect change in hash value of URL using JavaScript

前端 未结 3 1214
清酒与你
清酒与你 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:24

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

    const markup = `
            
  • ${limitRecipeTitle(recipe.title)}

    ${recipe.title}

    ${recipe.publisher}

  • `;

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

提交回复
热议问题