0

我正在尝试在我的网站中进行深层链接。我的意思是我可以去一个像这样的网址

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 我会看到变量

这有意义吗?

谢谢你的帮助

4

1 回答 1

2

不确定您是否找到了深度链接的方法。

以下对我有用。它基本上从 url 获取参数并形成一个状态并用它替换当前(初始)状态。

// 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
    );
}
于 2013-12-09T05:15:37.663 回答