gpt4 book ai didi

javascript - 使用 History.js 对不同的 url 更改做出不同的响应

转载 作者:行者123 更新时间:2023-11-28 02:40:26 24 4
gpt4 key购买 nike

我正在使用history.js,并且想在url更改时通过ajax调用内容。我可以正常工作,但问题是我需要页面根据状态更改时加载的 URL 做出不同的响应。例如,在本地范围内,我需要将与右侧导航中的 URL 相关的页面加载到它们旁边的内容区域中。如果 URL 更改为我所在部分之外的范围,我希望 ajax 调用将页面加载到包含整个部分(包括右侧导航)的容器中。如何使用 History.js 可靠地对 URL 做出不同的响应?

示例:

我有一些代码可以在单击右侧导航项时更改 URL:

var History = window.History;

$('#right-hand-nav a').on('click', function(event) {
var place = $(this).attr('href');

History.pushState("", "page title", place);
event.preventDefault();
});

...以及一些在 URL 更改时加载不同内容的代码:

History.Adapter.bind(window,'statechange',function() {
var State = History.getState()
subContent = $('#sub-content');

$.ajax({
url: State.url,
beforeSend : function() {
// Would start pre-loader code
},
success : function(result) {
// Would end pre-loader code
subContent.html(result);
}

});
});

但是,如果我希望 onstatechange 事件处理程序在新 URL 位于此子部分之外时做出不同的 react ,该怎么办?如果我希望它替换 $('#primary-content').html() 而不是 $('#sub-content').html() if新 URL 导致 AJAX 请求提取不属于 $('#sub-content')?:

的内容

基本 HTML:

<section id="primary-content">
<section id="sub-content">
</section>
<nav id="sub-navigation">
<ul>
<li>
<a href="#">Nav item</a>
</li>
<li>
<a href="#">Nav item</a>
</li>
<li>
<a href="#">Nav item</a>
</li>
</ul>
</nav>
</section>

当 URL 更改为: www.example.com/sub-section/page.html

<section id="primary-content">
<section id="sub-content">
<!-- ajax should load content here -->
</section>
<nav id="sub-navigation">
<ul>
<li>
<a href="#">Nav item</a>
</li>
<li>
<a href="#">Nav item</a>
</li>
<li>
<a href="#">Nav item</a>
</li>
</ul>
</nav>
</section>

当 URL 更改为: www.example.com/page.html

<section id="primary-content">
<!-- ajax should load content here -->
</section>

如何使用 history.js 安全地确定 URL 何时转到不同部分?您对这一变化有何 react ?

最佳答案

您可以在 History.js(这是一个相当低级的 API)之上使用路由器抽象,将 URL 路由到您的不同函数。例如,我编写了一个 History.js 路由库,名为 StateRouter.js 。它处于开发的早期阶段,但如果您发现它缺少解决您问题的功能,我很乐意听取您的意见。要了解 API 提供的功能,请查看“spec/StateRouterSpec.js”中的 Jasmine 测试。您可以像这样应用 StateRouter.js:

var router = new staterouter.Router();
router
.route('/', loadHomePage)
.route('/page.html', loadSection)
.route('/sub-section/page.html', loadSubsection);
// Perform routing of the current state
router.perform();

关于javascript - 使用 History.js 对不同的 url 更改做出不同的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12735606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com