基于带有#的url打开模态

Open modal based on url with #

本文关键字:模态 url 于带      更新时间:2023-09-26

当右片段在URL中时,我有两个模式要显示,因此domain.com#steg2加载model#steg2,domain.com#steg3加载model#steg3。

我的脚本:

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

我的模态就是这样构建的:

<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上。我做错了什么?站点正在使用bootstrap 3和jQuery。

经过一些尝试,我发现了以下代码来完成工作:

<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>    

我建议:

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);

参考文献:

  • JavaScript:
    • Array.prototype.indexOf()
    • window.location
  • jQuery:
    • on()

首先使用window.location.hash从url中获取哈希。这个值前面会加一个#。然后你可以直接把它用作jquery选择器。

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