twitter-bootstrap 使用 URL 和哈希切换 Bootstrap 模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24967735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Toggle Bootstrap modal with URL and hash
提问by lacoder
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!
我想使用带有哈希值的 URL 来调用特定的 Bootstrap 模式。换句话说,用户在 page1 上并单击 page2#hash 的链接,并且在 page2 加载时加载 #hash 模式。根据我在其他问答中读到的内容,我尝试了很多变体,但没有任何效果。我对 JS 完全没有经验,所以我很感激一些帮助!
Here's what I have:
这是我所拥有的:
Link on page1: <a href="/page2#myModal>
第 1 页上的链接: <a href="/page2#myModal>
HTML on page2:
第 2 页上的 HTML:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
...
</div>
Javascript on page2:
第 2 页上的 Javascript:
<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.
顺便说一句,<a href="#" data-toggle="modal" data-target="#myModal">当用户实际在第 2 页时调用模态就可以了。
回答by Patrick Evans
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.
此外,您可能不会等待 dom 准备好使用。如果您在页面底部或至少在您的模态 html 所在的下方没有该脚本,则无法找到它,因为它尚未创建。
<script>
//shortcut for $(document).ready
$(function(){
if(window.location.hash) {
var hash = window.location.hash;
$(hash).modal('toggle');
}
});
</script>

