Bootstrap 3.x:单击模式触发器后如何更改url? [英] Bootstrap 3.x: how to have url change upon clicking modal trigger?

查看:85
本文介绍了Bootstrap 3.x:单击模式触发器后如何更改url?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Bootstrap v3.3.5

我有一个使用网址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>

这将成功触发此模式

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

但是,URL不会更改为domain.com/companies#modal-add-company

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

URL 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. 将网址更改为domain.com/companies#modal-add-company,并且
  2. 如果我直接输入网址domain.com/companies#modal-add-company,则会显示模式信息
  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

推荐答案

使用jQuery,这可能是一个可行的解决方案

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);
 });

并假设您希望转义按钮仍然能够关闭模式,并更改整个代码块的url,如下所示:

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();
    });

有关如何使用模式关闭事件的信,请 https://stackoverflow.com/a/13201843/80353 .

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

这篇关于Bootstrap 3.x:单击模式触发器后如何更改url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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