Bootstrap 3.x: how to have url change upon clicking modal trigger?

懵懂的女人 提交于 2019-12-28 06:36:21

问题


Using Bootstrap v3.3.5

I have a webpage that is using the url domain.com/companies

This is my trigger for the modal in that webpage.

<a href="#modal-add-company" class="btn btn-effect-ripple btn-effect-ripple btn-success" data-toggle="modal"><i class="fa fa-plus"></i> New Company</a>

This will successfully trigger this modal

<div id="modal-add-company" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">

However, the url does not change to domain.com/companies#modal-add-company

Nor does the url domain.com/companies#modal-add-company actually trigger the modal on reload.

What do I need to do to have the following:

  1. change the url to domain.com/companies#modal-add-company whenever I trigger the modal and the modal is shown, and
  2. if i directly type the url domain.com/companies#modal-add-company, the modal is shown

回答1:


Using jQuery this could be a viable solution

$(document).ready(function(){
   $(window.location.hash).modal('show');
   $('a[data-toggle="modal"]').click(function(){
      window.location.hash = $(this).attr('href');
   });
});

Assuming you have a trigger to close the modal like this:

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>

You can add this below the code block above:

$('button[data-dismiss="modal"]').click(function(){
     var original = window.location.href.substr(0, window.location.href.indexOf('#'))
     history.replaceState({}, document.title, original);
 });

And assuming you want escape button to still be able to close the modal, and also change the url the whole code block would look like this:

    $(window.location.hash).modal('show');
    $('a[data-toggle="modal"]').click(function(){
        window.location.hash = $(this).attr('href');
    });

    function revertToOriginalURL() {
        var original = window.location.href.substr(0, window.location.href.indexOf('#'))
        history.replaceState({}, document.title, original);
    }

    $('.modal').on('hidden.bs.modal', function () {
        revertToOriginalURL();
    });

Credit to https://stackoverflow.com/a/13201843/80353 about how to use modal close event.




回答2:


Use this on onclick event of the button that triggers the modal

onclick="window.location.hash = 'modal-add-company';"

And write following script code after bootstrap.js

<script>
if(window.location.hash.substr(1) == 'modal-add-company'){
    $('#modal-add-company').modal('show');
}
</script>

It should work.



来源:https://stackoverflow.com/questions/34154370/bootstrap-3-x-how-to-have-url-change-upon-clicking-modal-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!