使用URL和哈希切换Bootstrap模式 [英] Toggle Bootstrap modal with URL and hash

查看:176
本文介绍了使用URL和哈希切换Bootstrap模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用带哈希的URL来调用特定的Bootstrap模式。换句话说,用户在page1上并点击指向page2 #hash的链接,并在加载page2时加载#hash模态。我已经根据我在其他Q / As中读到的内容尝试了很多变化,但没有任何效果。我对JS没有任何经验,所以我很感激一些帮助!

I'd like to use URLs with hashes to call specific Bootstrap modals. In other words, a user is on page1 and clicks on a link to page2#hash and the #hash modal loads when page2 loads. I've tried so many variations based on what I've read in other Q/As, but nothing has worked. I'm not at all experienced with JS, so I'd appreciate some help!

这就是我所拥有的:

第1页上的链接:< a href =/ page2#myModal>

第2页的HTML:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
  ...
</div>



第2页的Javascript:


Javascript on page2:

<script>
  if(window.location.hash) {
    var hash = window.location.hash;
    $("'" + hash + "'").modal('toggle');
  }
</script>



顺便说一下,< a href =#data-toggle =modaldata-target =#myModal> 当用户实际在第2页时,可以正常调用模态。


Incidentally, <a href="#" data-toggle="modal" data-target="#myModal"> works just fine to call the modal when the user is actually on page2.

推荐答案

您正在为选择器添加单引号,选择器不使用引号:

You are adding single quotes to your selector, selectors don't use quotes:

$("'" + hash + "'").modal('toggle');

应该是

$(hash).modal('toggle');

您也可能不等待dom准备好使用。如果您在页面底部没有该脚本,或者至少在您的模态html所在的位置以下,则无法找到该脚本,因为它尚未创建。

Also you might not be waiting for the dom to be ready to use. If you do not have that script at the bottom of the page or at least below where your modal html is, it won't be found as it is not created yet.

<script>
  //shortcut for $(document).ready
  $(function(){
      if(window.location.hash) {
          var hash = window.location.hash;
          $(hash).modal('toggle');
      }
  });
</script>

这篇关于使用URL和哈希切换Bootstrap模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆