2014-10-31 83 views
1

我有兩個模式我想顯示何時右邊的片段在URL中,所以domain.com#steg2加載模態#steg2和domain.com#steg3加載模態#steg3。基於URL打開模式#

我的腳本:

$(function() { 
    if (window.location.hash.indexOf("steg2") !== -1) { 
     $("#steg2").modal(); 
    } 
    if (window.location.hash.indexOf("steg3") !== -1) { 
     $("#steg3").modal(); 
    } 
}); 

這是我的情態動詞是如何buildt:

<div class="modal fade" id="steg2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> 


<div class="modal fade" id="steg3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> 

兩種模態都在同一頁/ URL。我究竟做錯了什麼?網站使用引導程序3和jQuery。

回答

0

首先通過window.location.hash從url獲取散列。該值將以#作爲前綴。然後你可以直接使用它作爲jquery選擇器。

var hash = window.location.hash; 
    if(hash != '') { 
      $(hash).modal(); 
    } 
1

我建議:

function hashModal() { 
    var stegs = ['steg2','steg3'], 
     hash = window.location.hash, 
     stegAt = stegs.indexOf(hash.replace('#',''); 
    if (stegAt > -1) { 
     $(hash + '.modal').modal(); 
    } 
} 

$(document).on('ready hashchange', hashModal); 

參考文獻:

+0

謝謝你,我想你的建議,但沒有模式顯示當我輸入domain.com#steg2的。關於我可能做錯什麼的想法? – mrleira 2014-10-31 21:07:54

3

一些試驗後,我發現這個代碼做的工作:

<script type="text/javascript"> 
jQuery(document).ready(function($) { 
var target = document.location.hash.replace("#", ""); 
if (target.length) { 
if(target=="steg1"){ 
    $('#steg1').modal('show'); 
} 
else if(target=="steg2"){ 
    $('#steg2').modal('show'); 
} 
else if(target=="steg3"){ 
    $('#steg3').modal('show'); 
} 
} 
else{  
} 
}); 
</script>