Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

javascript - Toggle Bootstrap modal with URL and hash

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!

Here's what I have:

Link on page1: <a href="/page2#myModal>

HTML on page2:

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


Javascript on page2:

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


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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

should be

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

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...