我正在开发一个基于单页(由于项目限制)并具有动态内容的简单应用程序。我理解动态内容,但我不明白的是如何设置一个脚本,div当 URL 中的哈希值发生变化时,该脚本会更改 a 的 html。
我需要一个 JavaScript 脚本才能这样工作:
网址:http://foo.com/foo.htmldiv 内容:<h1>Hello World</h1>
网址:http://foo.com/foo.html#foodiv 内容:<h1>Foo</h1>
这将如何工作?
请帮忙!谢谢。
我正在开发一个基于单页(由于项目限制)并具有动态内容的简单应用程序。我理解动态内容,但我不明白的是如何设置一个脚本,div当 URL 中的哈希值发生变化时,该脚本会更改 a 的 html。
我需要一个 JavaScript 脚本才能这样工作:
网址:http://foo.com/foo.htmldiv 内容:<h1>Hello World</h1>
网址: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)带有哈希标签的项目时,将触发哈希事件。要接收触发的哈希事件,我们必须在 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);
}
}
}