使用JavaScript检测URL哈希值的更改
Detect change in hash value of URL using JavaScript
我正在开发一个简单的应用程序,该应用程序基于单页(由于项目限制)并具有动态内容。我很理解动态内容,但我不明白的是,当URL中的哈希值发生变化时,如何设置一个脚本来更改div
的html。
我需要一个JavaScript脚本来这样工作:
Url:http://foo.com/foo.html
div内容:<h1>Hello World</h1>
Url:http://foo.com/foo.html#foo
div内容:<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)具有hash标记的项,将触发hash事件。要接收触发的哈希事件,我们必须在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);
}
}
}
相关文章:
- Steam Web API:I'我不知道该如何处理这个看起来像哈希的url来生成图像
- 在Javascript中实现对哈希值的暴力攻击
- 使用Javascript从url中获取空哈希值
- 如何使用JS重定向到具有哈希值的引用URL
- 单击一页滚动菜单时更改URL哈希值
- 如何获得新的哈希值的URL没有页面重新加载
- 使用JavaScript搜索URL的哈希值,而不是特定的字符串
- 需要移除url参数前的哈希值
- 在jquery的url(锚)中获得许多#哈希值
- 在单击事件/函数期间获取URL哈希值
- 将类切换到特定元素取决于URL的哈希值
- 在nodejs中通过url获取哈希值
- toState.Url值不是嵌套状态的绝对哈希值
- 当只有url哈希值发生变化时,我如何重新加载整个页面?
- 更改URL不会重新加载文档->如何检查哈希值
- 清除URL哈希值
- 在IE9浏览器返回按钮的url中更改了哈希值
- 使用JavaScript检测URL哈希值的更改
- 如果页面 URL 中存在哈希值,则添加类
- JQuery Ajax在url中添加哈希值