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

前端 未结 2 458
谎友^
谎友^ 2020-12-06 13:12

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 web

2条回答
  •  既然无缘
    2020-12-06 13:59

    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:

    
    

    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.

提交回复
热议问题