JS 參數傳遞的實際應用程式碼分析_javascript技巧

來源:互聯網
上載者:User
原因很簡單,在DOM中沒有id為msg_box的div標籤,該怎麼解決這個問題呢?
方案:
在所有頁面公用的頭部檔案header.tpl.html中寫入:
複製代碼 代碼如下:

<script>
function changMenu(index){
if(typeof getElementById("msg_box") == "object"){
//如果存在msg_box對象 則重新整理該頁的對象
showMenu(index);
}else{
//如果不存在 則重新導向到使用Ajax重新整理的頁面
window.location = "/index.html";
}
}
</script>

但是該項目index.html存在四個相同性質的頁面,都需要Ajax來重新整理,這樣就存在一個問題,當使用者點擊第三個欄目時,雖然可以回到index.html,但是無法重新整理內容到第三個欄目。這時有兩種解決方案:
方案1:
第一步:
在所有頁面公用的頭部檔案header.tpl.html中寫入:
複製代碼 代碼如下:

<script>
function changMenu(index){
if(typeof getElementById("msg_box") == "object"){
//如果存在msg_box對象 則重新整理該頁的對象
showMenu(index);
}else{
//如果不存在 則重新導向到使用Ajax重新整理的頁面
window.location = "/index.html?type="+index;
}
}
</script>

第二步:
改進showMenu函數
複製代碼 代碼如下:

function showMenu(index){
if(typeof getElementById("msg_box") == "object"){
//如果存在msg_box對象 則重新整理該頁的對象
......
}else{
url = window.location.href;
reg = /^(.*)\/index\.html\?type\=\d$/gi;
if(reg.test(url)){
//如果符合傳參數頁面的url。則擷取該參數
index = url.substr(url.length - 1);
......
}
}
}

方案2:
調用JS的cookie功能傳遞參數
在所有頁面公用的頭部檔案header.tpl.html中寫入:
複製代碼 代碼如下:

<script>
function changMenu(){
index = getCookie("index");
if(index == null) index = 1;
if(typeof getElementById("msg_box") == "object"){
//如果存在msg_box對象 則重新整理該頁的對象
showMenu(index);
}else{
setCookie("index", index);
//如果不存在 則重新導向到使用Ajax重新整理的頁面
window.location = "/index.html";
}
}
function setCookie(name, value){  
 var Then = new Date()  
 Then.setTime(Then.getTime() + 1*3600000 ) //小時  
 document.cookie = name+"="+value+";expires="+Then.toGMTString();  
}
function getCookie(name)
{
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr != null) return unescape(arr[2]); return null;
}
 
</script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.