我想在我的网站中进行深层链接。我的意思是,我可以去一个像
这样的网址http://test.madeup.com/?campaign=funkyNew
如果继续这样做,它将改变页面显示并将funkynew活动带到顶部。
我一直在阅读history.js的例子并且有几个问题。
所以示例代码就是这样的
// Establish Variables
var History = window.History, // Note: We are using a capital H instead of a lower h
State = History.getState(),
$log = $('#log');
// Log Initial State
History.log('initial:', State.data, State.title, State.url);
// Bind to State Change
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
// Log the State
var State = History.getState(); // Note: We are using History.getState() instead of event.state
History.log('statechange:', State.data, State.title, State.url);
alert("stateChanged - run function");
});
// Prepare Buttons
var
buttons = document.getElementById('buttons'),
scripts = [
'History.pushState({state:1,rand:12345}, "Test", "?campaign=funkyNew"); '
],
buttonsHTML = '';
// Add Buttons
for ( var i=0,n=scripts.length; i<n; ++i ) {
var _script = scripts[i];
buttonsHTML +=
'<li><button onclick=\'javascript:'+_script+'\'>'+_script+'</button></li>';
}
buttons.innerHTML = buttonsHTML;
这可以通过单击更改URL的按钮来实现,然后显示变量。这没问题。
我需要做的是使用funkynew直接转到url并获取变量并让它运行一个函数。
显然,它现在不会起作用,因为历史只是在按下按钮时创建的 - 所以我怎么能在开始时把它们放在那里,这样如果我直接去funkyCampaign,即从另一个url,我看到变量< / p>
这有意义吗?
感谢您的帮助
丹
答案 0 :(得分:2)
不确定你是否找到了深层链接的方法。
以下适用于我。它基本上从url获取params并形成一个状态并用它替换当前(初始)状态。
// Bind to State Change
History.Adapter.bind(window,'statechange',function(){
// Log the State
var State = History.getState();
History.log('statechange:', State.data, State.title, State.url);
alert("stateChanged - run function");
});
var utils = utils || {};
utils.getParameterByName: function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
//On page load route to appropriate screen
if(urlParamSection = utils.getParameterByName('section')){
History.replaceState({
section: urlParamSection
}, // This is state's data
'MySite - ' + urlParamSection.toUpperCase(), //Title to the state
window.location.protocol+"//"+window.location.host + "?section=" + urlParamSection // this is actually the page load url
);
}